-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay-051.cpp
117 lines (98 loc) · 2.2 KB
/
Day-051.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include<iostream>
using namespace std;
void merge(int *arr,int s ,int e){
int mid = s + (e-s)/2;
int len1 = mid - s + 1;
int len2 = e - mid;
int *first = new int[len1];
int *second = new int[len2];
// copy values
int mainArrayIndex = s;
for(int i=0;i <len1;i++){
first [i] = arr[mainArrayIndex++];
}
mainArrayIndex = mid+1;
for (int i =0;i <len2;i++){
second[i]=arr[mainArrayIndex++];
}
// merge two sorted array
int index1 = 0;
int index2 = 0;
mainArrayIndex = s;
while(index1 < len1 && index2 < len2){
if(first[index1]<second[index2]){
arr[mainArrayIndex++] = first[index1++];
}
else{
arr[mainArrayIndex++] = second[index2++];
}
}
while(index1 < len1){
arr[mainArrayIndex++] = first[index1++];
}
while(index2 < len2){
arr[mainArrayIndex++] = second[index2++];
}
}
void mergeSort(int *arr, int s, int e){
// base case
if(s >= e){
return;
}
int mid = s + (e-s)/2;
//left part
mergeSort(arr,s,mid);
//right part
mergeSort(arr,mid+1,e);
// merging
merge(arr,s,e);
}
int partition(int arr[],int s, int e){
int pivot = arr[s];
int cnt = 0;
for(int i= s+1; i <=e;i++){
if(arr[i]<= pivot){
cnt++;
}
}
// right place of povit
int pivotIndex = s +cnt;
swap(arr[pivotIndex],arr[s]);
// left and right wala part sambhal lete hai
int i = s,j = e;
while(i<pivotIndex && j>pivotIndex){
while(arr[i]<pivot){
i++;
}
while(arr[j] > pivot){
j--;
}
if(i<pivotIndex && j>pivotIndex){
swap(arr[i++],arr[j--]);
}
}
return pivotIndex;
}
void quickSort(int arr[],int s,int e){
// base case
if(s>=e){
return;
}
//partion
int p = partition(arr,s,e);
// left part
quickSort(arr,s,p-1);
//right part
quickSort(arr,p+1,e);
}
int main (){
int arr[5] = {2,5,1,6,9};
int n = 5;
// mergeSort(arr,0,n-1);
quickSort(arr,0,n-1);
for(int i = 0;i<n;i++){
cout << arr[i] << " ";
}
cout << endl;
return 0;
}