merge sort python

Solutions on MaxInterview for merge sort python by the best coders in the world

showing results for - "merge sort python"
Giulio
27 Apr 2017
1def merge_sort(arr):
2    # The last array split
3    if len(arr) <= 1:
4        return arr
5    mid = len(arr) // 2
6    # Perform merge_sort recursively on both halves
7    left, right = merge_sort(arr[:mid]), merge_sort(arr[mid:])
8
9    # Merge each side together
10    return merge(left, right, arr.copy())
11
12
13def merge(left, right, merged):
14
15    left_cursor, right_cursor = 0, 0
16    while left_cursor < len(left) and right_cursor < len(right):
17      
18        # Sort each one and place into the result
19        if left[left_cursor] <= right[right_cursor]:
20            merged[left_cursor+right_cursor]=left[left_cursor]
21            left_cursor += 1
22        else:
23            merged[left_cursor + right_cursor] = right[right_cursor]
24            right_cursor += 1
25            
26    for left_cursor in range(left_cursor, len(left)):
27        merged[left_cursor + right_cursor] = left[left_cursor]
28        
29    for right_cursor in range(right_cursor, len(right)):
30        merged[left_cursor + right_cursor] = right[right_cursor]
31
32    return merged
Amy
28 Jun 2019
1def mergeSort(myList):
2    if len(myList) > 1:
3        mid = len(myList) // 2
4        left = myList[:mid]
5        right = myList[mid:]
6
7        # Recursive call on each half
8        mergeSort(left)
9        mergeSort(right)
10
11        # Two iterators for traversing the two halves
12        i = 0
13        j = 0
14        
15        # Iterator for the main list
16        k = 0
17        
18        while i < len(left) and j < len(right):
19            if left[i] < right[j]:
20              # The value from the left half has been used
21              myList[k] = left[i]
22              # Move the iterator forward
23              i += 1
24            else:
25                myList[k] = right[j]
26                j += 1
27            # Move to the next slot
28            k += 1
29
30        # For all the remaining values
31        while i < len(left):
32            myList[k] = left[i]
33            i += 1
34            k += 1
35
36        while j < len(right):
37            myList[k]=right[j]
38            j += 1
39            k += 1
40
41myList = [54,26,93,17,77,31,44,55,20]
42mergeSort(myList)
43print(myList)
Leonardo
09 Jan 2017
1def mergesort(list1):
2    if len(list1) >1 :
3    
4        mid = len(list1)//2
5        left_list = list1[:mid]
6        right_list = list1[mid:]
7        mergesort(left_list) #Using recursion down here for the sub list
8        mergesort(right_list) #Using recursion down here for the sub list
9        i = 0
10        j = 0
11        k = 0
12        while i<len(left_list) and j<len(right_list):
13            if left_list[i]< right_list[j]:
14                list1[k] = left_list[i]
15                i+=1
16                k+=1
17            else:
18                list1[k] = right_list[j]
19                j+=1
20                k+=1
21        while i < len(left_list): # I did this as for the end condition of above loop as when i or j will be equal to len(left/right list)  
22            list1[k] = left_list[i]
23            i+=1
24            k+=1
25
26        while j < len(right_list):
27            list1[k] = right_list[j]
28            j+=1
29            k+=1
30#Start watching from here and then as when function call will come then go check function
31n = int(input("Enter how many element you want in the list : "))
32list1 = [int(input()) for i in range(n)]
33mergesort(list1)
34print("sorted list : " + str(list1))
Candy
07 Jun 2020
1// @see https://www.youtube.com/watch?v=es2T6KY45cA&vl=en
2// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
3
4function merge(list, start, midpoint, end) {
5    const left = list.slice(start, midpoint);
6    const right = list.slice(midpoint, end);
7    for (let topLeft = 0, topRight = 0, i = start; i < end; i += 1) {
8        if (topLeft >= left.length) {
9            list[i] = right[topRight++];
10        } else if (topRight >= right.length) {
11            list[i] = left[topLeft++];
12        } else if (left[topLeft] < right[topRight]) {
13            list[i] = left[topLeft++];
14        } else {
15            list[i] = right[topRight++];
16        }
17    }
18}
19
20function mergesort(list, start = 0, end = undefined) {
21    if (end === undefined) {
22        end = list.length;
23    }
24    if (end - start > 1) {
25        const midpoint = ((end + start) / 2) >> 0;
26        mergesort(list, start, midpoint);
27        mergesort(list, midpoint, end);
28        merge(list, start, midpoint, end);
29    }
30    return list;
31}
32
33mergesort([4, 7, 2, 6, 4, 1, 8, 3]);
Antonio
17 Mar 2016
1def mergeSort(arr):
2
3    if len(arr) > 1:
4
5        a = len(arr)//2
6
7        l = arr[:a]
8
9        r = arr[a:]
10
11        # Sort the two halves
12
13        mergeSort(l)
14
15        mergeSort(r) 
16
17        b = c = d = 0
18
19        while b < len(l) and c < len(r):
20
21            if l[b] < r[c]:
22
23                arr[d] = l[b]
24
25                b += 1
26
27            else:
28
29                arr[d] = r[c]
30
31                c += 1
32
33            d += 1
34
35        while b < len(l):
36
37            arr[d] = l[b]
38
39            b += 1
40
41            d += 1
42
43        while c < len(r):
44
45            arr[d] = r[c]
46
47            c += 1
48
49            d += 1
50
51
52def printList(arr):
53
54    for i in range(len(arr)):
55
56        print(arr[i], end=" ")
57
58    print()
59 
60
61# Driver program
62
63if __name__ == '__main__':
64
65    arr = [0,1,3,5,7,9,2,4,6,866
67    mergeSort(arr) 
68
69    print("Sorted array is: ")
70
71    printList(arr)
72
73 
74
queries leading to this page
to write a python program merge sort examples of merge sort pythonmerge list python2 way merge sort python codesort merge in pythonmerge sort split arrays down pythonnatural merge sort pythonmerge sort python coewhich of the following functions could be used in merge sort to merge two sorted lists 3fmerge sort function python inbuiltphyton merge sortneed for sorting in merge pythonmerge sort method python merge sort array pythonmerge sortfunction pythonmarge sort in python merge sortmerge sort in python 3how to use merge sort in pythonmerge sort python codemerge sort algorithmcin pythonfunction mergesort 28nums 29 7b 2f 2f write merge sort code here 7dmerge sort descending order python geeksforgeeksmerge sort big omerge sort merge function pythonmerge sorrblock merge sort implementation in pythonpython in place merge sortpython program for merge sort4 python program for merge sort merge soring c 2b 2btwo way merge sort pythonmerge sort on listrecursive tree of odd even merge sortmerge sort pytohnmerge sort time and space complexitymerge sort commerge sort pyhmerge sort in pythonmerge sort recursive javamerge sort python real pythonmerge sort c 2b 2bmerge sort algorithm implementation pythonmergesort 5cmerge sort algorithm pythonmerge soprtmergesort with pythonmerge sort python best implementationc 2b 2b code for merge sortmerge sort code in pythonmerge sort python recursiveaverage complexity of merge sortmerge sort amerge sort algorithm defhow to write merge sort in pythonwhat is a merge sort3 way merge sort in pythonpython code for merge sortmergesort table by element pythonuse of merge sortfor the merge sort algorithm discussed in class 2c if the following change is made 2c the worst case runtime would bemerge sort c 2b 2b global functionselection insertion merge sort c 2b 2bmerge sort in javamerge sort program in pythonalgorithm of merge sort in pythonmerge packages algorithms pythonpython mergesortdetermine the appropriate sorting algorithm corresponding to the below function 3a function 28m 2cn 29 7bif 28m 3cn 29 7bmid 3d 28m 2bn 29 2f2 3b sort 28m 2cmiddle 29 3b sort 28middle 2b1 2cn 29 3b sort 28m 2cmiddle 2cn 29 3b 7d 7d 2ac 2b 2b merge sort understanding merge sortmerge sort complexitymerge sort workingmergesort with odd listsprogram for merge sort in pythonmerge sort logic in pythonmerge array algorithm pythonmerge sort example with stepsmerge sort divide and conquer pythonmerge sort in python using functionmerge sort using recursion pythonmerge sort pseudocodepython program for merge sort algorithmmergesor in pythonmerge sort with pythonmerge sort in placemerge sort examplesmergesort oythonmerge sort java recursionpython merge sort examplehow merge sort in python worksmerge sort python 3how does merge sort workmerge sorty pythonrecursive merge sort cpptime complexity of merge sort in pythonrecursive merge sort pythonmerge sort baeldungmerge sort python 3 8merge sort examplemergesort algorithm pythonpython algo merge sor thow does a merge sort workmerge sortypython merge sort recursive implementatonmerge sort definitionmerge sorted arraymerge sort in c 2b 2b programhow does the mergesort workmergesort python codemerge sort in pyhtonmerge sort recursive pythonpython mergesorywhat is merge sort used formerge sortemerge sort algorithm explainedmerge sortusing fucntions pythonmerge sort algorithm python line by linehow to merge sortpython code for merge sort sortmergesort cmergesort implementation c 2b 2ba recursive function that sorts a sequence of numbers in ascending order using the merge function above merge sort algorithm python codemarge sort in cmerge sort in matrixmerge sort function in c 2b 2bmerfe sort pythonmerge sort sorted listusing python how to implement the program with the program with list 2c merging 2c sortingmerge sort inpythonmerge sort python3merge sort pymerge sort help in pythonsort the array using merge sort in pythonmerge sorting a listmarge sort in pythonwhat is merge sort in pythoneasy merge sort program in pythonimplement following merge sort algorithm using recursion print passes of merging algorithm mergesort pythonmerge sort in pythinmerge sort tutorialcode for merge sort in python7th call to mergemerge sort is in placearray merge program in pythob2 way merge sort pythonmerge sort in cpp codepython program for implementation of merge sortmerge function in python complexitywrite a function called merge that takes two already sorted lists of possibility different lengths 2c and merge them into a single sorted list using sorted methodmergesort pyhtonpython3 mergesortalgorithm for merge sort in pythonjava merge sort simplemerge sortfuction to split the list in merge sort c languagemerge sort array pythonwrite a program to sort an array using merge sort phythonmerge sort in python in short codepython code merge sort algorithmsimplement merge sort pythonmerge sort and sort in c 2b 2bfull implementation merge sort c 2b 2bmerge sort in python programpython program to merge sortmergesort complexity in already ascending orderhow to implement merge sortmerge sort algorithmpython merge sort codeare there any python library that use merge sortmerge sort sort in pythonsyntax python merge sortwhat is merge sort algorithmmeerge sort program to check no of passes required forr sortig an arraypython merge sort tutorialhow to perform a merge sortmerge sort source codein merge sort 2c you createmerge algorithm pythonmarge sort algorithm desgin in pythonpython complexity of merge sortwhy doesn 27t python use merge sort for sort 28 29merge sort python codemerge sort python 3fmerge sort demoquick implementation of merge sort in pythonhow to sort list in python using mergesortc 2b 2b merge sorta c code for merge sort use tabbing with binary search in the merging process merge sort in pythonic waymerge sort python implementationmerge sort algorithmhow to do merge sort in pythonmerge sort theorytime complexity in pythonof merge sortmerge code pythonmerge sort listmerge sort pyhtonmerge sort al on pythonhow to implement merge sort in pythonpython merge sort functionmerge sort cppmerge sort about merge sort in pythonmergesort diagrammergesort codepython easy merge sortpython merge sort librarymerge sort python explanationpython merge sort algorithmmerge sort explainedmerge sort real pythonmerge sort program in c 2b 2bmerge sort in python listmerge sort using auxiliarywrite a program to implement merge sort in python merge sort python librarymerg sort in pythonmerge sort function in pythonmerge sort cspace complexity of merge sortmerge sort in c 2b 2berge sort pythonmerge sor tpythonerge sort code merge sort en pythonmerge sorting in pythonmerge sort on odd number of elementsimplementation of merge sort algorithm in c 2b 2bmerge and sort algorithmpython merge sort complexitymergesort for pythonmergesortmerge sort code pythonsort function in python uses merge sortpython merge sort implementationmerge sort agorithm pythonmerge sort python algorithm merge sortmerge sort algorithm in pythonpython merge sort recursionhow merge sort worksmergesort python programmergesort pytc merge sort void 2amerge sort codemerge sort algorithmcode for merge sortclever mergesort in pythonsample code example for merge sort in pythonwhat is merge sortthe merge sort algorithmmerge in pythonmerge lists pythonpython merge sortmerge sort algorithm 3fmerge sort c 2b 2b programmerge sort in simple python9 running merge sort on an array of size n which is already sorted is 2amerge sortedmerge sort in pythonmerge sort function cwrite a program include binary search and merge sort in pythonmerging sortingmerge sort algomerge function in merge sort pythonmerge sort in python using recursionpython merge sort programmerge sort code in cmerger sort cmerge sort pythonmergesort python3what is merge sort python 3fexplain merge sortmerge sort implementation in clist merge sort explainedmerge sort en pythonmergesort cpp codemerge sort psuedocodemerge sort function ordermerge sort in simple pythonhow to merge sort in pythonmerge sort in python codec 2b 2b merge sort codemerge pythonpython merge sortpython recursive merge sortmerge sort explanationmerge sort recursion pythonprogramming merge sort in pythonmerge sort algorithm in python with codepg2 merge sortingmerge sort odd numbermerge sort ascending orderpython merge sort explainedmerge sort ascending c 2b 2bpython merge sort inbuiltmerge sort python indonesiamerge sort in pytonmerge sort using pythonpthon merge sortwrite a python program to implement merge sort merge how pythonfusion sort pythonmerge sort python practicehow to merge sort an algorithm listpython code merge sortalgorithmsgeeks for geeks merge sort recursivec 2b 2b merge sort recursive merge sort merge algorithmmerge sort program in python 3merge sort code in c 2b 2bmerge sort pythonsimple merge sort program in pythonmerge sort solvemerge sort in cppmerge sort implementpython binary search and merge sortpython merge osrtmerge sort array algomerge sort forpython code datastructures mergeaverage tc of merge sorthow to sort in merge sortlet p be a mergesort program to sort numbers in ascendinng order on a unknown data structure which take o 28n 5e2 29 time to find the mid element 2c rest property is unknown then recurrence relation for the same is 3fmergesort in pythonsorteed merge pythonmerged sortmerge sorth in pythonmerge sortzwhat python method do merge sort on listmerge sort algorithm decresing merge sortwhere we use merge sortmerge sort and time complexity in pythontrace merge sort on the following set of data 3a b f z g p w s l c mmergesort 28 29 pythonmerge fort using pythonpseudocode for merge sort in pythonmerge sort complexity pythonmerge sort wikimerge sortingmerge sort python complexityalgorithm paradigm of merge sort pythonmerge sorte pythonsorting inpython merge sortmerge sort code pythonmerge sort algorithm in placewhat is the time complexity of a merge sort in pythonmerge sort python programbig o notation merge sortpython mege sortmergesort wikiquicksort pythonrogram for merge sort in pythonmerge sort simple python code3 way merge sort pythonmerge sort using recursion pyhtonhow to merge sort pythonmerge sort expressed mathematicallymerge sort with pypandas merge sort neededmerge sort python practieimplement merge sort in pythonpythonic merge sortsuppose we split the elements unevenly 28not in the middle 29 when applying merge sort the resultant will be same as 3a selection sort bucket sort bubble sort insertion sortpython list in order mergemerge sort for arraylist in pythonpython mergefunction mergesort 28nums 29 7b 2f 2f write merge sort code here how to make a merge sort in pythonalgorithm sort fusion pythonmerge sort pythonmergesort complexityhow to use sorted array from merge sort pythonmergesort function in c 2b 2bmerge sort in place pythonhow to indicate order in merge sortmergesort implementation javamerge sort using pythnmerge sort in cnumpy library for merge sortwhat is merge sort 3fmerge sort ipython merge sort cormenmerge sort recursive c 2b 2b codepython code merge fusion algorithmsmerge sort javamergesort in cmerge sort algorithm geekforgeeks 3fmerge sort algorithm examplehow to understand to write merge sort algorithm pythonsorting string merge sortsimple merge sort in pythonmerge sort more efficent waypython function that implements a merge sortpython simple merge sort algorithmmerge sort pythionsort 28 29 in python merge sortmerge sort sort complexitycode for merge sort in cmerge method for merge sortmerge sorotmerge sort using queue in pythonmerge sprt merge sort in python simple programmerge sort in python explainedhow merge sort works 3fitterative merge sort pythonapplication of mergesort where gfgmerge sort to sort arraymerge sort python modulegeeksforgeeks merge sortdef merge sortmerge sort 5cmerge sort nedirmerge sort array pythonillustrate the operation of merge sort on the array a 3d 7b3 2c 41 2c 52 2c 26 2c 38 2c 57 2c 9 2c 49 7d explain the algorithm neatly step by step also give a graphical view of the solutionwrite a program to implement merge sort in pythonmerge sort python 5dmerge sort implementation in pythonpython merge sort pythonmerge sort algorithm simple code in pythonmerge sort python