c++ code for quicksort
#include <iostream>
using namespace std;
void swap(int a, int b) {
int t = *a;
a = b;
*b = t;
}
int partition(int arr[], int low, int high) {
int pivot = arr[high];
int i = (low - 1);
for (int j = low; j <= high - 1; j++) {
if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
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);
}
}
int main() {
int arr[] = { 64, 34, 25, 12, 22, 11, 90 };
int n = sizeof(arr) / sizeof(arr[0]);
quicksort(arr, 0, n - 1);
cout << "Sorted array: \n";
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
Let's go through the code step by step:
Header inclusion: The code includes the
<iostream>
header, which is necessary for input/output operations in C++.Namespace: The line
using namespace std;
allows us to use standard library functions and objects without explicitly specifying thestd
namespace.Swap function: The
swap
function takes two integer pointers and swaps their values by using a temporary variablet
.Partition function: The
partition
function takes an arrayarr
, a starting indexlow
, and an ending indexhigh
. It chooses the last elementarr[high]
as the pivot and rearranges the array such that all elements smaller than the pivot are placed before it, and all elements greater than the pivot are placed after it. It returns the index of the pivot element.Quicksort function: The
quicksort
function is a recursive function that performs the quicksort algorithm on the given array. It takes the arrayarr
, a starting indexlow
, and an ending indexhigh
. It first callspartition
to find the pivot element and then recursively callsquicksort
on the left and right subarrays, excluding the pivot.Main function: The
main
function is the entry point of the program. It declares an arrayarr
and initializes it with some values. It calculates the size of the array usingsizeof
andsizeof(arr[0])
. It then callsquicksort
to sort the array. Finally, it prints the sorted array using afor
loop.
The quicksort algorithm works by selecting a pivot element and partitioning the array around it. It repeatedly partitions the subarrays until the entire array is sorted. The pivot element is chosen using various techniques, and in this code, the last element of the array is used as the pivot.
I hope this explanation helps! Let me know if you have any further questions.