-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec10_mergesort.cpp
88 lines (70 loc) Β· 1.52 KB
/
lec10_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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
// insertion , selection , bubble sort - T.C :- O(n^2)
//merge sort - T.C :- O(nlog2(n))
//S.C :- O(n)
#include<iostream>
#include<vector>
using namespace std;
void print ( int arr[] ,int n)
{
for(int i = 0 ;i<n;i++)
{
cout<<arr[i];
}
}
void merge( int arr[] , int start , int mid , int end)
{
vector<int> temp (end - start +1);
int left = start , right = mid +1 , index = 0 ;
while(left <=mid && right <=end)
{
if(arr[left]<=arr[right])
{
temp[index] = arr[left];
index++ , left++;
}
else{
temp[index] = arr[right];
index++ , right++;
}
}
// left
while(left<=end)
{
temp[index] = arr[left];
index++ , left++;
}
while(right <= end)
{
temp[index] = arr[right];
index++ , right++;
}
index = 0 ;
while(start <=end)
{
arr[start] = temp[start];
start++ , index++ ;
}
}
void mergesort(int arr[] , int start , int end )
{
if(start == end)//only one element
{
return ;
}
//divide
int mid = start + (end - start)/2;
mergesort(arr , start , mid);//left
mergesort(arr , mid+1 , end) ;//right
merge(arr , start , mid , end);
}
int main()
{
int arr[] = { 6 , 3 , 5 , 2 , 2 , 8 , 1 , 3 , 2 , 9};
cout<<"Before Sorting "<<endl;
print(arr , 10);
// start , size-1
mergesort(arr , 0 , 9);
cout<<"After Sorting "<<endl;
print(arr , 10);
return 0 ;
}