Posts Merge Sort (geeksforgeeks - SDE Sheet)
Post
Cancel

Merge Sort (geeksforgeeks - SDE Sheet)

PROBLEM DESCRIPTION

Given an array arr[], its starting position l and its ending position r. Sort the array using merge sort algorithm.

geeksforgeeks

SOLUTION

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution
{
    void merge(int arr[], int l, int m, int r)
    {

        int[] out = new int[r-l+1];

        int i = l;
        int j = m+1;

        int idx = 0;

        while(i<=m && j<=r){

            if(arr[i] < arr[j]){
                out[idx++] = arr[i++];
            }else{
                out[idx++] = arr[j++];
            }

        }

        while(i <= m)
            out[idx++] = arr[i++];

        while(j <= r)
            out[idx++] = arr[j++];

        for(int k=0; k<out.length; k++){
            arr[k+l] = out[k];
        }

    }

    void mergeSort(int arr[], int l, int r)
    {

        if( l >= r)
            return;

        int m = l + (r-l) / 2;

        mergeSort(arr, l, m);
        mergeSort(arr, m+1, r);

        merge(arr, l, m, r);

    }
}
This post is licensed under CC BY 4.0 by the author.