merge sort

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

showing results for - "merge sort"
Tidiane
09 Apr 2019
1MergeSort(arr[], l,  r)
2If r > l
3     1. Find the middle point to divide the array into two halves:  
4             middle m = l+ (r-l)/2
5     2. Call mergeSort for first half:   
6             Call mergeSort(arr, l, m)
7     3. Call mergeSort for second half:
8             Call mergeSort(arr, m+1, r)
9     4. Merge the two halves sorted in step 2 and 3:
10             Call merge(arr, l, m, r)
Katharine
13 Mar 2017
1//merge sort
2#include <iostream>
3
4using namespace std;
5void merge(int arr[],int start,int mid,int end)
6{
7    int n1=mid-start+1;
8    int n2=end-mid;
9    int l[n1],m[n2];
10    for(int i=0;i<n1;i++)
11    {
12        l[i]=arr[start+i];
13    }
14    for(int j=0;j<n2;j++)
15    {
16        m[j]=arr[mid+1+j];
17    }
18    int i=0;
19    int j=0;
20    int k=start;
21    while(i<n1&&j<n2)
22    {
23        if(l[i]<m[j])
24        {
25            arr[k]=l[i];
26            k++;
27            i++;
28        }
29        else
30        {
31            arr[k]=m[j];
32            k++;
33            j++;
34        }
35    }
36    while(i<n1)
37    {
38        arr[k]=l[i];
39        k++;
40        i++;
41    }
42    while(j<n2)
43    {
44        arr[k]=m[j];
45        k++;
46        j++;
47    }
48}
49void mergesort(int arr[],int start,int end)
50{
51    if(start<end)
52    {
53        int mid=(start+end)/2;
54        mergesort(arr,start,mid);
55        mergesort(arr,mid+1,end);
56        merge(arr,start,mid,end);
57    }
58}
59void display(int arr[],int n)
60{
61    for(int i=0;i<n;i++)
62    {
63        cout<<arr[i]<<" ";
64    }
65    cout<<endl;
66}
67
68int main()
69{
70    int n;
71    cout<<"enter the size of the array:"<<endl;
72    cin>>n;
73    cout<<"enter the elements of the array:"<<endl;
74    int arr[n];
75    for(int i=0;i<n;i++)
76    {
77        cin>>arr[i];
78    }
79    cout<<"array as it is:"<<endl;
80    display(arr,n);
81    cout<<"sorted array:"<<endl;
82    mergesort(arr,0,n-1);
83    display(arr,n);
84    return 0;
85}
86
Felix
07 Jan 2018
1class Sort 
2{
3    void merge(int arr[], int left, int middle, int right)
4    {
5        int low = middle - left + 1;                    //size of the left subarray
6        int high = right - middle;                      //size of the right subarray
7 
8        int L[] = new int[low];                             //create the left and right subarray
9        int R[] = new int[high];
10
11        int i = 0, j = 0;
12 
13        for (i = 0; i < low; i++)                               //copy elements into left subarray
14        {
15            L[i] = arr[left + i];
16        }
17        for (j = 0; j < high; j++)                              //copy elements into right subarray
18        {
19            R[j] = arr[middle + 1 + j];
20        }
21        
22 
23        int k = left;                                           //get starting index for sort
24        i = 0;                                             //reset loop variables before performing merge
25        j = 0;
26
27        while (i < low && j < high)                     //merge the left and right subarrays
28        {
29            if (L[i] <= R[j]) 
30            {
31                arr[k] = L[i];
32                i++;
33            }
34            else 
35            {
36                arr[k] = R[j];
37                j++;
38            }
39            k++;
40        }
41 
42        while (i < low)                             //merge the remaining elements from the left subarray
43        {
44            arr[k] = L[i];
45            i++;
46            k++;
47        }
48 
49        while (j < high)                           //merge the remaining elements from right subarray
50        {
51            arr[k] = R[j];
52            j++;
53            k++;
54        }
55    }
56 
57
58    void mergeSort(int arr[], int left, int right)       //helper function that creates the sub cases for sorting
59    {
60        int middle;
61        if (left < right) {                             //sort only if the left index is lesser than the right index (meaning that sorting is done)
62            middle = (left + right) / 2;
63 
64            mergeSort(arr, left, middle);                    //left subarray
65            mergeSort(arr, middle + 1, right);               //right subarray
66 
67            merge(arr, left, middle, right);                //merge the two subarrays
68        }
69    }
70 
71    void display(int arr[])                 //display the array
72    {  
73        for (int i=0; i<arr.length; ++i) 
74        {
75            System.out.print(arr[i]+" ");
76        } 
77    } 
78
79    public static void main(String args[])
80    {
81        int arr[] = { 9, 3, 1, 5, 13, 12 };
82        Sort ob = new Sort();
83        ob.mergeSort(arr, 0, arr.length - 1);
84        ob.display(arr);
85    }
86}
87
Lya
05 May 2018
1void merge(int arr[], int l, int m, int r)
2    {
3         int n=r-l+1,temp[n];
4         int i=l,j=m+1,k=0;
5         while(i<=m and j<= r)
6         {
7             if(arr[i]< arr[j]){
8                temp[k++] = arr[i++];
9             else
10                temp[k++] = arr[j++];
11         }
12         while(i<=m)
13            temp[k++] = arr[i++];
14         while(j<=r)
15            temp[k++] = arr[j++];
16         int ind= 0;
17         for(int i=l;i<=m;i++)
18             arr[i] = temp[ind++];
19         for(int j=m+1;j<=r;j++)
20            arr[j] = temp[ind++];
21    }
22    
23    void mergeSort(int arr[], int l, int r)
24    {
25       if(l<r)
26       {
27           int mid = (r+l)/2;
28           mergeSort(arr,l,mid);
29           mergeSort(arr,mid+1,r);
30           merge(arr,l,mid,r);
31       }
32    }
Mariangel
06 Jun 2016
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]);
Anna
06 Feb 2020
1# Python3 recursive merge sort algorithm -> O(n*log(n))
2def merge_sort(A):
3    def merge(l, r):
4        i = j = 0
5        n = []  # merging container
6        while i < len(l) or j < len(r):
7
8            # if no more elements to the right,
9            # add remaining left elements
10            if i == len(l):
11                n.extend(r[j:])
12                break
13
14            # if no more elements to the left,
15            # add remaining right elements
16            if j == len(r):
17                n.extend(l[i:])
18                break
19
20            # if elements left on both sides,
21            # add smaller element
22            a, b = l[i], r[j]
23            if a < b:
24                n.append(a)
25                i += 1
26            else:
27                n.append(b)
28                j += 1
29
30        return n
31
32    # divide list down to single-elements
33    s = len(A)
34    if s > 1:
35        s //= 2
36        l = merge_sort(A[:s])  # split left
37        r = merge_sort(A[s:])  # split right
38        return merge(l, r)  # merge sides in order
39    else:
40        return A
Valeria
21 Feb 2019
1Step 1if it is only one element in the list it is already sorted, return.
2Step 2 − divide the list recursively into two halves until it can no more be divided.
3Step 3 − merge the smaller lists into new list in sorted order.
4
Maja
10 Jan 2017
1Given array is 
212 11 13 5 6 7 
3Sorted array is 
45 6 7 11 12 13
queries leading to this page
merge sort demowhat is merge sortsort mergesorthow does merge sort work 3fwhat is merge sort used formerge sort source codewhere we use merge sortfor the merge sort algorithm discussed in class 2c if the following change is made 2c the worst case runtime would bemergesort wikimerge sort gein merge sort 2c you createmerge sort program in c 2b 2bmerge sort worstmerge sort algorithm in placemerge sort complexity analysisdescribe merge sortmergesort implementation c 2b 2bmerge sort works usingmarge sort in cmerge sort algorithmebig o notation merge sortmergesort pythonmerge sort sort algorithmmerge soring c 2b 2bmergesort 27average tc of merge sortmerge sort recursive javamerge sort and sort in c 2b 2bmerge sort is in placegeeks for geeks merge sort recursivemerge sort amergesort implementation javaa c code for merge sort use tabbing with binary search in the merging process c 2b 2b merge sortmerge sort ascending c 2b 2bmerge sort time and space complexitymerge sort algorithmfull implementation merge sort c 2b 2bmerge sort concepthow to sort in merge sorthow merge sort worksmerge sort solvemerge sort theoryc 2b 2b code for merge sortmerge sort standardmerge sort using auxiliarymerge sortzmerge sortmerge sort big omerge sort algorithm 23how to perform a merge sorthow merge sort is sortedmerge sorting merge sort in placeselection insertion merge sort c 2b 2bmerge sort array algoc 2b 2b merge sort codemerge sort algomerge sort algorithm mergesort inmerge sort c 2b 2bmergesort codesorting string merge sortmerge sorrworking of merge sortc 2b 2b merge sort recursive merge sort mergehow does merge sort workmerge sort explainedmerge sort codejava merge sort simplemerge sort ca merge sort merger sort cmerge sort in matrixc 2b 2b merge sort space complexity of merge sortmerge sort in cpp code merge sortmerge sort pythonmerge sort imerge sort ordermerge sort workmerge sort comwhen we use merge sortmerge sort sortmerge sort function in c 2b 2bmerge sort o 28how to merge sortmerge sort more efficent waymergesort function in c 2b 2bmerge sort expressed mathematicallymerge sort how does a merge sort workmerge sort cppfunction mergesort 28nums 29 7b 2f 2f write merge sort code here merge sort algorithm explainedmerge sort priciple 5cmerge sort code in cc merge sort void 2ause of merge sortmerge sort ascending ordermerging sortingis sort 28 29 a merge sortmerge sort simple definitionmerge sort nedircode for merge sort in cmergesort csort merge sort merge and sort algorithmhow merge sort works 3fmerge sort function cmerge sort tmerge sort in cmerge sort complexitymerge sort complemergesort cpp codem way merge sortwhat is merge sort 3fmerge sort recursive c 2b 2b codemerge sort example with stepsmerge sorty9 running merge sort on an array of size n which is already sorted is 2awhen is merge sortmerge sort in javamerge sort techniquemerge sortingmerge sortsortdefine merge sortwhat is merge sort algorithmmerge sort implementation in cmerge sort is in place sort merge sort python complexityapplication of mergesort where gfgmerge sort algorithmmergesortmergesort 5cmerge sort in c 2b 2b programmerge sort in place 3faverage complexity of merge sortmerge sort mergingmergesort complexity in already ascending ordersort using merge sortdetermine 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 2amergesort in cmerge sort meaningmerge sort baeldungsee merge sorthow to implement merge sorterge sort codemerge sort in c 2b 2bmerge sort code in c 2b 2bmerge sort uhow does the mergesort workmerge and sortmerge sort javawhat is a 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 3fmerge sort workingrecursive merge sort cppdef merge sortsort mergemerged sortmerge sort algorithm geekforgeeks 3fmerge sorteimplement merge sortmerge sort wikimerge sort 5calgorithm merge sortmergesort complexitymerge sort algorithm exampleexplain merge sortmerge sort algorithmimplement following merge sort algorithm using recursion print passes of merging algorithm merge sort in algorithmhow to indicate order in merge sortmerge sort exampledefinition of merge sortunderstanding merge sortcode for merge sortmerge sort algorithm defmerge sort pseudocodemerge sort explanationwhat is the merge sortmerge sort to sort arraymerge sort functionmerge sort java recursionmerge sort forimplementation of merge sort algorithm in c 2b 2bmerge sprt founder of merge sortwhen is merge sort usedmerge sort algorithm 3fmerge sort algorithm 5cmerge sort definitionmerge sort implementmerge sort sort complexitymerge sort c 2b 2b programmerge order bymerge sort psuedocodewho created merge sortmerge sort in cppmerge sort 5chow merge sort workmerge sorted arraygeeksforgeeks merge sortmerge sort hsmerge sort tutorialmerge method for merge sorthow does merge sort woeksmerge sort