-
Notifications
You must be signed in to change notification settings - Fork 0
/
quick sort.cpp
65 lines (52 loc) · 1.36 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
#include<iostream>
using namespace std;
void swap(int *a, int *b){
int temp = *a;
*a=*b;
*b=temp;
};
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int left = low + 1;
int right = high;
while (left <= right) {
while (left <= right && arr[left] <= pivot) {
left++;
}
while (left <= right && arr[right] > pivot) {
right--;
}
if (left < right) {
swap(&arr[left], &arr[right]);
}
}
swap(&arr[low], &arr[right]);
return right;
}
void quicksort(int arr[], int low, int high) {
if (low < high) {
int pivotIndex = partition(arr, low, high);
quicksort(arr, low, pivotIndex - 1);
quicksort(arr, pivotIndex + 1, high);
}
}
int main(){
int m;
int arr[20];
cout << "How many elements you want to enter: "<<endl;
cin >> m;
for (int i = 0; i < m; i++) {
cout << "Enter value for arr[" << i << "]: ";
cin >> arr[i];
}
cout << "Array elements before swapping: "<<endl;
for (int i = 0; i < m ; i++) {
cout << arr[i] << " "<<endl;
}
quicksort(arr, 0,m - 1);
cout << "Array elements after swapping: ";
for (int i = 0; i < m; i++) {
cout << arr[i] << " ";
}
return 0;
}