-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquick-sort.cpp
91 lines (72 loc) · 1.43 KB
/
quick-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
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
#include<bits/stdc++.h>
using namespace std;
int partition(int arr[], int low, int high){
// int pivot = arr[low];
// int count = 0;
// for(int i=low+1;i<=high;i++){
// if(arr[i]<=pivot){
// count++;
// }
// }
// //place pivot at right place
// int pivotIdx = low+count;
// swap(arr[pivotIdx],arr[low]);
// int l = low;
// int h = high;
// while(l<pivotIdx && h>pivotIdx){
// while (arr[l]<=pivot)
// {
// l++;
// }
// while(arr[h]>pivot){
// h--;
// }
// if(l<pivotIdx && h>pivotIdx){
// swap(arr[l++],arr[h--]);
// }
// }
// int i = low;
// int h = high;
// while(i<h){
// do{
// i++;
// }
// while (arr[i]<=pivot);
// do
// {
// h--;
// } while (arr[h]>pivot);
// if(i<h){
// swap(arr[i],arr[h]);
// }
// }
// swap(arr[low],arr[h]);
// return pivot;
int pivot = arr[low];
int i = low + 1;
for (int j = low + 1; j <= high; j++) {
if (arr[j] < pivot) {
swap(arr[i], arr[j]);
i++;
}
}
swap(arr[low], arr[i - 1]);
return i - 1;
}
void mergesort(int arr[],int low, int high){
if(low>=high){
return;
}
int pivot = partition(arr,low,high);
mergesort(arr,low,pivot-1);
mergesort(arr,pivot+1,high);
}
int main(){
int arr[5] = {5,3,1,43,6};
int n =5;
mergesort(arr,0,n-1);
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}