TheAlgorithms-C-Plus-Plus/sorting/quick_sort.cpp

59 lines
1.3 KiB
C++
Raw Normal View History

2016-09-06 16:55:19 +08:00
/* C implementation QuickSort */
2019-08-21 10:10:08 +08:00
#include <iostream>
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
2019-08-21 10:10:08 +08:00
for (int j = low; j < high; j++) {
2016-09-06 16:55:19 +08:00
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot) {
i++; // increment index of smaller element
2019-08-21 10:10:08 +08:00
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
2016-09-06 16:55:19 +08:00
}
}
2019-08-21 10:10:08 +08:00
int temp = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp;
2016-09-06 16:55:19 +08:00
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
2019-08-21 10:10:08 +08:00
int p = partition(arr, low, high);
2016-09-06 16:55:19 +08:00
quickSort(arr, low, p - 1);
quickSort(arr, p + 1, high);
}
}
void show(int arr[], int size) {
for (int i = 0; i < size; i++) std::cout << arr[i] << "\n";
2016-09-06 16:55:19 +08:00
}
2019-08-21 10:10:08 +08:00
2016-09-06 16:55:19 +08:00
// Driver program to test above functions
int main() {
2016-09-06 16:55:19 +08:00
int size;
std::cout << "\nEnter the number of elements : ";
2016-09-06 16:55:19 +08:00
std::cin >> size;
2016-09-06 16:55:19 +08:00
int *arr = new int[size];
2019-08-21 10:10:08 +08:00
std::cout << "\nEnter the unsorted elements : ";
2016-09-06 16:55:19 +08:00
for (int i = 0; i < size; ++i) {
std::cout << "\n";
std::cin >> arr[i];
2016-09-06 16:55:19 +08:00
}
quickSort(arr, 0, size);
std::cout << "Sorted array\n";
2016-09-06 16:55:19 +08:00
show(arr, size);
delete[] arr;
2016-09-06 16:55:19 +08:00
return 0;
}