-
Notifications
You must be signed in to change notification settings - Fork 0
/
MergeSort.cpp
63 lines (49 loc) · 1.21 KB
/
MergeSort.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
50
51
52
53
54
55
56
57
58
59
/*
* MergeSort.cpp
*
* Created on: Apr 22, 2014
* Author: shashi
*/
#include "CommonHeader.h"
#include <cstring>
static int iter=0;
void merge_arrays(int *arr, int *left, int *right,int size)
{
int mid_point = size/2;
int left_index = 0, right_index = 0, arr_index =0;
while( left_index < mid_point && right_index < size - mid_point)
{
if(left[left_index] < right[right_index])
{
arr[arr_index++] = left[left_index++];
}
else
{
arr[arr_index++] = right[right_index++];
}
iter++;
}
while(left_index < mid_point)
{
arr[arr_index++] = left[left_index++];
iter++;
}
while(right_index < size - mid_point)
{
iter++;
arr[arr_index++] = right[right_index++];
}
}
int invokeFunction(int inputArr[],int arrSize)
{
int mid_point = size / 2 ;
int left[mid_point], right[size - mid_point];
if(size == 1 || size == 0)
return;
memcpy(left, arr, sizeof(left));
memcpy(right, arr+mid_point, sizeof(right));
merge_sort(left, mid_point);
merge_sort(right, size - mid_point);
merge_arrays(arr, left, right, size);
return iter;
}