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

68 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>
2016-09-06 16:55:19 +08:00
using namespace std;
2019-08-21 10:10:08 +08:00
int partition(int arr[], int low, int high)
2016-09-06 16:55:19 +08:00
{
2019-08-21 10:10:08 +08:00
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
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)
{
2019-08-21 10:10:08 +08:00
i++; // increment index of smaller element
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)
{
2019-08-21 10:10:08 +08:00
for (int i = 0; i < size; i++)
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()
{
int size;
2019-08-21 10:10:08 +08:00
cout << "\nEnter the number of elements : ";
2016-09-06 16:55:19 +08:00
2019-08-21 10:10:08 +08:00
cin >> size;
2016-09-06 16:55:19 +08:00
int arr[size];
2019-08-21 10:10:08 +08:00
cout << "\nEnter the unsorted elements : ";
2016-09-06 16:55:19 +08:00
for (int i = 0; i < size; ++i)
{
2019-08-21 10:10:08 +08:00
cout << "\n";
cin >> arr[i];
2016-09-06 16:55:19 +08:00
}
quickSort(arr, 0, size);
2019-08-21 10:10:08 +08:00
cout << "Sorted array\n";
2016-09-06 16:55:19 +08:00
show(arr, size);
return 0;
}