-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_sort.cpp
49 lines (42 loc) · 1.08 KB
/
merge_sort.cpp
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
#include <iostream>
using namespace std;
void merge(int arr[], int start, int mid, int end){
int tmp_arr[end-start+1];
int left = start;
int right = mid+1;
int idx = 0;
while(left <= mid && right <= end){
if(arr[left] <= arr[right]){
tmp_arr[idx++] = arr[left++];
}
else
tmp_arr[idx++] = arr[right++];
}
while(left <= mid)
tmp_arr[idx++] = arr[left++];
while(right <= end)
tmp_arr[idx++] = arr[right++];
for(int i = end-start; i>=0; i--, end--)
arr[end] = tmp_arr[i];
}
void merge_sort(int arr[], int start, int end){
if(start >= end)
return;
int mid = start + (end-start)/2;
merge_sort(arr, start, mid);
merge_sort(arr, mid+1, end);
merge(arr, start, mid, end);
}
void test_merge_sort_one(){
int arr[] = {32,44,11,89,1,0};
int len = sizeof(arr)/sizeof(arr[0]);
merge_sort(arr, 0, len-1);
cout << "Sorted Array = ";
for(int i =0; i<len;i++)
cout << arr[i] << ",";
cout << endl;
}
int main(){
test_merge_sort_one();
return 0;
}