Skip to content

Instantly share code, notes, and snippets.

@Daemon-Devarshi
Last active April 25, 2020 06:58
Show Gist options
  • Select an option

  • Save Daemon-Devarshi/f16e15b82d8d1629dd521676b6292ab5 to your computer and use it in GitHub Desktop.

Select an option

Save Daemon-Devarshi/f16e15b82d8d1629dd521676b6292ab5 to your computer and use it in GitHub Desktop.

Revisions

  1. Daemon-Devarshi revised this gist Apr 25, 2020. 1 changed file with 16 additions and 0 deletions.
    16 changes: 16 additions & 0 deletions merge_sort.py
    Original file line number Diff line number Diff line change
    @@ -1,4 +1,20 @@
    # divide and conquer approach
    def mergeSort(array):
    # divides the array into sub-parts
    length = len(array)
    if length == 1 or length == 0:
    # returns leaf node
    return array
    # obtain mid index
    mid = length // 2
    # obtain left array
    leftArray = mergeSort(array[0: mid])
    # obtain right array
    rightArray = mergeSort(array[mid: length])
    # sort left and right array
    return sortedMerge(leftArray, rightArray)

    # conquer approach
    def sortedMerge(leftArray, rightArray):
    # combines 2 arrays passed
    # initial setup
  2. Daemon-Devarshi created this gist Apr 25, 2020.
    37 changes: 37 additions & 0 deletions merge_sort.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@

    def sortedMerge(leftArray, rightArray):
    # combines 2 arrays passed
    # initial setup
    leftArrayLength = len(leftArray)
    rightArrayLength = len(rightArray)
    sortedArray = []
    leftIndex = 0
    rightIndex = 0

    while leftIndex < leftArrayLength and rightIndex < rightArrayLength:
    # If left array element smaller than right array element
    # add left array element
    if leftArray[leftIndex] < rightArray[rightIndex]:
    sortedArray.append(leftArray[leftIndex])
    # increment leftIndex
    leftIndex += 1
    else:
    # right array element smaller than left array element
    # add right array element
    sortedArray.append(rightArray[rightIndex])
    # increment rightIndex
    rightIndex += 1

    # append remaining left softed array
    while leftIndex < leftArrayLength:
    sortedArray.append(leftArray[leftIndex])
    # increment leftIndex
    leftIndex += 1

    # append remaining right softed array
    while rightIndex < rightArrayLength:
    sortedArray.append(rightArray[rightIndex])
    # increment leftIndex
    rightIndex += 1

    return sortedArray