Code for qsort in C with swap

Here is an example of C code for implementing qsort using a swap function:

#include <stdio.h>

// Swap function
void swap(int a, int b) {
    int temp = *a;
    a = b;
    *b = temp;
}

// Partition function
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);
}

// Quicksort function
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);
    }
}

// Main function
int main() {
    int arr[] = { 10, 7, 8, 9, 1, 5 };
    int n = sizeof(arr) / sizeof(arr[0]);

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

    quickSort(arr, 0, n - 1);

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

    return 0;
}

Explanation:

  1. The code starts with the inclusion of the stdio.h header file, which provides input/output functions like printf.

  2. The swap function takes two integer pointers as arguments and swaps their values using a temporary variable. This function is used to swap the elements during the partitioning process.

  3. The partition function takes an array, arr, and two indices, low and high, as arguments. It selects the last element of the array, arr[high], as the pivot and rearranges the other elements such that all elements smaller than the pivot are moved to the left and all elements greater than the pivot are moved to the right. The function returns the index of the pivot element.

  4. The quickSort function recursively calls itself to sort the array. It takes the array, arr, and the indices low and high as arguments. It first calls the partition function to find the pivot index, pi, and then recursively calls quickSort on the subarrays before and after the pivot index.

  5. The main function initializes an array, arr, with some values, and calculates the size of the array, n, using the sizeof operator.

  6. It then prints the original array using a for loop and the printf function.

  7. The quickSort function is called with the array, arr, and the indices 0 and n - 1 to sort the array.

  8. Finally, the sorted array is printed using another for loop and the printf function.

The code demonstrates the implementation of the qsort algorithm using the swap function for element swapping and the partition function for partitioning the array. The quickSort function recursively calls itself to sort the subarrays.