📌  相关文章
📜  教资会网络 | UGC NET CS 2017 年 1 月至 2 日 |问题 7(1)

📅  最后修改于: 2023-12-03 15:39:55.533000             🧑  作者: Mango

UGC NET CS 2017 January to February | Question 7

Introduction

UGC NET CS is an exam conducted by the National Testing Agency that assesses the eligibility of candidates for lectureship and Junior Research Fellowship in Computer Science. Question 7 from the January-February 2017 exam is a programming question that requires the implementation of a merge sort algorithm.

Merge Sort Algorithm

The Merge Sort algorithm is a popular sorting algorithm used to sort arrays and lists by dividing them recursively into smaller subarrays until they are small enough to be sorted efficiently using a swapping algorithm. The algorithm works by dividing the input into halves, recursively sorting each half, and then merging the two sorted halves to produce the final sorted output.

Pseudo code
1. Divide the unsorted list into n sub-lists, each containing one element
2. Repeatedly merge sublists to produce new sorted sublists until there is only one sublist remaining
Implementation

Here is an implementation of Merge Sort in Python:

def merge_sort(arr):
  if len(arr) > 1:
    mid = len(arr) // 2
    left_arr = arr[:mid]
    right_arr = arr[mid:]
    
    # Recursive calls
    merge_sort(left_arr)
    merge_sort(right_arr)
    
    # Merging sub-arrays
    i = j = k = 0
    while i < len(left_arr) and j < len(right_arr):
      if left_arr[i] < right_arr[j]:
        arr[k] = left_arr[i]
        i += 1
      else:
        arr[k] = right_arr[j]
        j += 1
      k += 1
      
    while i < len(left_arr):
      arr[k] = left_arr[i]
      i += 1
      k += 1
    
    while j < len(right_arr):
      arr[k] = right_arr[j]
      j += 1
      k += 1
Conclusion

The implementation of Merge Sort requires dividing the input recursively and merging the sub-arrays in a sorted order. Merge Sort is a fast and efficient algorithm for sorting arrays due to its recursive approach.