-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMerge sort (In-place algorithm).cpp
More file actions
64 lines (49 loc) · 1.09 KB
/
Merge sort (In-place algorithm).cpp
File metadata and controls
64 lines (49 loc) · 1.09 KB
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
60
61
62
63
64
/*
MERGE SORT
This is inplace merge sort algorithm for merge sort.
Inplace algorithm has space complexity of O(1), i.e. they use constant space.
*/
#include<iostream>
using namespace std;
//function merge() for merging two half array segments
void merge(int a[], int low, int mid, int high)
{
int temp[10];
int i=low;
int j= mid+1;
int k=low;
while( (i<=mid) && (j<=high) )
{
if(a[i]<=a[j])
temp[k++]=a[i++];
else
temp[k++] = a[j++];
}
while(i<=mid)
temp[k++] = a[i++];
while(j<=high)
temp[k++] = a[j++];
for(i=low;i<=high;i++)
a[i] = temp[i];
}
//function part() for making partitions of the given array into two halves.
void part(int arr[], int low, int high)
{
int mid;
if(low!=high)
{
mid = (low+high)/2;
part(arr,low,mid);
part(arr,mid+1,high);
merge(arr,low,mid,high);
}
}
int main()
{
int arr[10]={5,2,3,6,4,1,8,9,7,10}, low, high, size;
size = sizeof(arr)/sizeof(arr[0]);
part(arr,0,size-1);
cout<<"\nSorted array is : ";
for(int i = 0 ; i < size ; i++)
cout<<arr[i]<<" ";
}