NEP -DAA -DESIGN AND ANALYSIS OF ALOGRITHM

PROGRAM 1 PROGRAM 2 PROGRAM 3 PROGRAM 4 PROGRAM 5 PROGRAM 6 PROGRAM 7 PROGRAM 8 PROGRAM 9 PROGRAM 10 PROGRAM 11 PROGRAM 12

PART B

PROGRAM B1 PROGRAM B2 PROGRAM B3 PROGRAM B4 PROGRAM B5 PROGRAM B6 PROGRAM B7 PROGRAM B8 . . .

 
   #.7.Write a program to implement Merge sort algorithm for sorting a list of integers in ascending order.



def merge_sort(arr):
   
    if len(arr) <= 1:
        return arr
    
    
    mid = len(arr) // 2
    left_half = arr[:mid]
    right_half = arr[mid:]
    
    
    left_sorted = merge_sort(left_half)
    right_sorted = merge_sort(right_half)
    
   
    return merge(left_sorted, right_sorted)

def merge(left, right):
    sorted_list = []
    i = j = 0
    
   
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            sorted_list.append(left[i])
            i += 1
        else:
            sorted_list.append(right[j])
            j += 1
    
    
    sorted_list.extend(left[i:])
    sorted_list.extend(right[j:])
    
    return sorted_list

# Test program
if __name__ == "__main__":
    arr = [38, 27, 43, 3, 9, 82, 10]
    print("Original array:", arr)
    sorted_arr = merge_sort(arr)
    print("Sorted array:", sorted_arr)