In this implementation of quick sort algorithm, we have first selects a pivot element from the array and then partitions the array into two subarrays based on whether the elements are less than or greater than the pivot. It then recursively sorts the subarrays using the same process until the entire array is sorted. You can also learn the bubble sort algorithm.
#include <iostream>
#include <algorithm>
using namespace std;
void quickSort(int arr[], int left, int right) {
int i = left, j = right;
int pivot = arr[(left + right) / 2];
/* partition */
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
swap(arr[i], arr[j]);
i++;
j--;
}
}
/* recursion */
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
int main() {
int arr[] = {4, 5, 1, 6, 2, 7, 3, 8};
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
/* print the sorted array */
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
return 0;
}
Thanks for visiting.