73 lines
1.2 KiB
C++
73 lines
1.2 KiB
C++
#include <iostream>
|
|
using namespace std;
|
|
|
|
|
|
int partition(int arr[], int start, int end) {
|
|
int pivot = arr[start];
|
|
|
|
int count = 0;
|
|
for (int i = start + 1; i <= end; i++) {
|
|
if (arr[i] <= pivot){
|
|
count++;
|
|
}
|
|
}
|
|
|
|
// Giving pivot element its correct position
|
|
int pivotIndex = start + count;
|
|
swap(arr[pivotIndex], arr[start]);
|
|
|
|
// Sorting left and right parts of the pivot element
|
|
int i = start, j = end;
|
|
|
|
while (i < pivotIndex && j > pivotIndex) {
|
|
while (arr[i] <= pivot) {
|
|
// Find index of the first element from left that is higher than pivot
|
|
i++;
|
|
}
|
|
|
|
while (arr[j] > pivot) {
|
|
// Find index of the first element from right that is lower than pivot
|
|
j--;
|
|
}
|
|
|
|
if (i < pivotIndex && j > pivotIndex) {
|
|
swap(arr[i], arr[j]);
|
|
i++;
|
|
j--;
|
|
}
|
|
}
|
|
|
|
return pivotIndex;
|
|
}
|
|
|
|
|
|
void quickSort(int arr[], int low, int high) {
|
|
if (low < high) {
|
|
int pi = partition(arr, low, high);
|
|
|
|
quickSort(arr, low, pi - 1);
|
|
quickSort(arr, pi + 1, high);
|
|
}
|
|
}
|
|
// 4 1 3 5 2
|
|
// 5 1 3 4 2
|
|
// 2 1 3 4 5
|
|
// 1 2 3 4 5
|
|
|
|
|
|
|
|
int main() {
|
|
int N = 50;
|
|
int arr[N];
|
|
for (int i = 0; i < N; i++) {
|
|
arr[i] = N - i;
|
|
}
|
|
|
|
quickSort(arr, 0, N - 1);
|
|
|
|
for (int i = 0; i < N; i++) {
|
|
cout << arr[i] << " ";
|
|
}
|
|
cout << endl;
|
|
return 0;
|
|
} |