Quicksort in C: Implementation Guide

The quicksort algorithm is a commonly used sorting algorithm that works by partitioning the data into two separate parts during each iteration of the sorting process, with one part containing all elements smaller than the other part. These two parts are then sorted individually, recursively repeating the process until the entire sequence is ordered.

Here is an example code in C language for implementing the quicksort algorithm.

#include <stdio.h>

void quickSort(int arr[], int left, int right) {
    int i = left, j = right;
    int pivot = arr[(left + right) / 2];

    while (i <= j) {
        while (arr[i] < pivot) {
            i++;
        }
        while (arr[j] > pivot) {
            j--;
        }
        if (i <= j) {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
            j--;
        }
    }

    if (left < j) {
        quickSort(arr, left, j);
    }
    if (i < right) {
        quickSort(arr, i, right);
    }
}

int main() {
    int arr[] = {12, 34, 23, 45, 56, 67, 78, 89, 90, 11};
    int n = sizeof(arr) / sizeof(arr[0]);

    quickSort(arr, 0, n - 1);

    printf("Sorted array: ");
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }

    return 0;
}

In the code above, the quickSort function implements the logic of the quicksort algorithm, where ‘left’ represents the starting index of the array and ‘right’ represents the ending index. In the main function, we define an array ‘arr’ and call the quickSort function to sort it, and finally print the sorted result.

Note: The example code above is just one way to implement it, in actual applications, optimization and improvement may be needed based on specific circumstances.

bannerAds