📜  Merge_sort - Python (1)

📅  最后修改于: 2023-12-03 14:44:15.594000             🧑  作者: Mango

Merge Sort - Python

Merge sort is a popular sorting algorithm that uses a divide-and-conquer method to sort an array or list of elements. It is a stable sorting algorithm, meaning that two elements with equal keys stay in their original order after sorting.

Algorithm

The merge sort algorithm works by recursively dividing the input list or array into smaller subarrays, sorting each subarray, and merging the sorted subarrays back together until the original list is fully sorted.

  1. Divide the unsorted array into n subarrays, each containing one element (base case).
  2. Repeat until there is only one sorted array:
    1. Merge adjacent subarrays to produce new sorted subarrays (merge step).
    2. Repeat until there is only one sorted subarray.
  3. Return the sorted array.
Example Code in Python
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left_half = arr[:mid]
        right_half = arr[mid:]

        merge_sort(left_half)
        merge_sort(right_half)

        i, j, k = 0, 0, 0
        while i < len(left_half) and j < len(right_half):
            if left_half[i] < right_half[j]:
                arr[k] = left_half[i]
                i += 1
            else:
                arr[k] = right_half[j]
                j += 1
            k += 1

        while i < len(left_half):
            arr[k] = left_half[i]
            i += 1
            k += 1

        while j < len(right_half):
            arr[k] = right_half[j]
            j += 1
            k += 1

    return arr

The merge_sort function takes an unsorted array as input and returns the sorted array. The if statement checks if the array contains more than one element. If so, it recursively calls merge_sort on the left and right halves of the array. Once the base case is reached (i.e., the array contains only one element), the while loop merges adjacent subarrays by comparing the first elements of each subarray and placing the smaller element in the output array until all elements are merged.

Performance

The time complexity of merge sort is O(n log n), which makes it a relatively efficient sorting algorithm for large data sets. However, merge sort requires additional memory to store the sorted subarrays during the merge step, which can be a disadvantage on systems with limited memory.

Conclusion

Merge sort is a popular sorting algorithm that uses a divide-and-conquer method to sort an array or list of elements. It is a stable sorting algorithm with a time complexity of O(n log n). The example Python code above demonstrates how to implement the merge sort algorithm in practice.