C Online Compiler
Example: Quick Sort using Recursion in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Quick Sort using Recursion #include <stdio.h> // Function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } /* * This function takes the last element as pivot, places * the pivot element at its correct position in sorted * array, and places all smaller (than pivot) to left * of pivot and all greater elements to right of pivot. */ int partition(int arr[], int low, int high) { // Step 1: Choose the pivot (last element in this implementation) int pivot = arr[high]; // Index of smaller element and indicates the right position of the pivot found so far int i = (low - 1); // Step 2: Iterate through the array from low to high-1 for (int j = low; j <= high - 1; j++) { // If current element is smaller than the pivot if (arr[j] < pivot) { i++; // Increment index of smaller element swap(&arr[i], &arr[j]); // Swap current element with element at i } } // Step 3: Place the pivot element at its correct sorted position swap(&arr[i + 1], &arr[high]); return (i + 1); // Return the partitioning index } /* * The main function that implements QuickSort * arr[] --> Array to be sorted, * low --> Starting index, * high --> Ending index */ void quickSort(int arr[], int low, int high) { // Step 1: Base case for recursion if (low < high) { // Step 2: pi is partitioning index, arr[pi] is now at right place int pi = partition(arr, low, high); // Step 3: Recursively sort elements before partition and after partition quickSort(arr, low, pi - 1); // Sort left sub-array quickSort(arr, pi + 1, high); // Sort right sub-array } } // Function to print an array void printArray(int arr[], int size) { for (int i = 0; i < size; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); quickSort(arr, 0, n - 1); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS