How to write code for the quicksort algorithm in C++?
#include <iostream>
#include <vector>
void quickSort(std::vector<int>& arr, int low, int high) {
if (low < high) {
int pivot = arr[low];
int i = low + 1;
int j = high;
while (i <= j) {
if (arr[i] <= pivot) {
i++;
} else if (arr[j] > pivot) {
j--;
} else {
std::swap(arr[i], arr[j]);
}
}
std::swap(arr[low], arr[j]);
quickSort(arr, low, j - 1);
quickSort(arr, j + 1, high);
}
}
int main() {
std::vector<int> arr = {5, 2, 9, 3, 7, 1, 8, 4, 6};
quickSort(arr, 0, arr.size() - 1);
std::cout << "Sorted array: ";
for (int num : arr) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
This code implements the quick sort algorithm to sort an array of integers. It recursively divides the array into two parts, sorts each part, and finally obtains a sorted array. In the main function, we define an integer array and call the quickSort function to sort it, then output the sorted result.
More tutorials
Sort the Java Collections using the sort() method.(Opens in a new browser tab)
2D array for C++ implementation(Opens in a new browser tab)
How to Delete Elements from an Array in Java(Opens in a new browser tab)
How can we use strlen in C language to calculate the length of an array?(Opens in a new browser tab)