mergge sort c 2b 2b

Solutions on MaxInterview for mergge sort c 2b 2b by the best coders in the world

showing results for - "mergge sort c 2b 2b"
Silvana
13 Jan 2017
1#include <iostream>
2using namespace std;
3void merge(int *,int, int , int );
4void merge_sort(int *arr, int low, int high)
5{
6    int mid;
7    if (low < high){
8        //divide the array at mid and sort independently using merge sort
9        mid=(low+high)/2;
10        merge_sort(arr,low,mid);
11        merge_sort(arr,mid+1,high);
12        //merge or conquer sorted arrays
13        merge(arr,low,high,mid);
14    }
15}
16// Merge sort 
17void merge(int *arr, int low, int high, int mid)
18{
19    int i, j, k, c[50];
20    i = low;
21    k = low;
22    j = mid + 1;
23    while (i <= mid && j <= high) {
24        if (arr[i] < arr[j]) {
25            c[k] = arr[i];
26            k++;
27            i++;
28        }
29        else  {
30            c[k] = arr[j];
31            k++;
32            j++;
33        }
34    }
35    while (i <= mid) {
36        c[k] = arr[i];
37        k++;
38        i++;
39    }
40    while (j <= high) {
41        c[k] = arr[j];
42        k++;
43        j++;
44    }
45    for (i = low; i < k; i++)  {
46        arr[i] = c[i];
47    }
48}
49// read input array and call mergesort
50int main()
51{
52    int myarray[30], num;
53    cout<<"Enter number of elements to be sorted:";
54    cin>>num;
55    cout<<"Enter "<<num<<" elements to be sorted:";
56    for (int i = 0; i < num; i++) { cin>>myarray[i];
57    }
58    merge_sort(myarray, 0, num-1);
59    cout<<"Sorted array\n";
60    for (int i = 0; i < num; i++)
61    {
62        cout<<myarray[i]<<"\t";
63    }
64}
65
similar questions
queries leading to this page
mergge sort c 2b 2b