Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

code for merge sort

# MergeSort in Python

def mergeSort(array):
    if len(array) > 1:

        #  r is the point where the array is divided into two subarrays
        r = len(array)//2
        L = array[:r]
        M = array[r:]

        # Sort the two halves
        mergeSort(L)
        mergeSort(M)

        i = j = k = 0

        # Until we reach either end of either L or M, pick larger among
        # elements L and M and place them in the correct position at A[p..r]
        while i < len(L) and j < len(M):
            if L[i] < M[j]:
                array[k] = L[i]
                i += 1
            else:
                array[k] = M[j]
                j += 1
            k += 1

        # When we run out of elements in either L or M,
        # pick up the remaining elements and put in A[p..r]
        while i < len(L):
            array[k] = L[i]
            i += 1
            k += 1

        while j < len(M):
            array[k] = M[j]
            j += 1
            k += 1


# Print the array
def printList(array):
    for i in range(len(array)):
        print(array[i], end=" ")
    print()


# Driver program
if __name__ == '__main__':
    array = [6, 5, 12, 10, 9, 1]

    mergeSort(array)

    print("Sorted array is: ")
    printList(array)
Comment

PREVIOUS NEXT
Code Example
Python :: cuda memory in pytorch 
Python :: python check for alphanumeric characters 
Python :: Group based sort pandas 
Python :: Python - How To Count Occurrences of a Character in a String 
Python :: convex hull python 
Python :: python sum 
Python :: time in python code 
Python :: solidity compiler for python 
Python :: url_for 
Python :: replace multiple column values pandas 
Python :: creating class and object in python 
Python :: enumerate in range python 
Python :: count no of nan in a 2d array python 
Python :: skimage local threshold 
Python :: python undefined 
Python :: Read the entire text file using the read() function 
Python :: create virtual env pyhton3 
Python :: raw input python 
Python :: Change Python interpreter in pycharm 
Python :: pandas not a time nat 
Python :: cv2 opencv-python imshow while loop 
Python :: numpy reshape 
Python :: appending objects to a list contained in a dictionary python 
Python :: django create view 
Python :: re.match python 
Python :: flask api with parameter 
Python :: how to change key to value and versa in python dictionary 
Python :: file open in python 
Python :: remove key from dictionary 
Python :: unsplash python 
ADD CONTENT
Topic
Content
Source link
Name
7+6 =