C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Arrays in C

Quick Sort Program

C Program: Quick Sort Program

C

#include <stdio.h>

 

// Function to swap two elements

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];  // Choose last element as pivot

    int i = (low - 1);      // Index of smaller element

 

    for (int j = low; j < high; j++) {

        if (arr[j] <= pivot) {

            i++;

            swap(&arr[i], &arr[j]);

        }

    }

 

    swap(&arr[i + 1], &arr[high]);

    return (i + 1);

}

 

// Quick Sort function

void quickSort(int arr[], int low, int high) {

    if (low < high) {

        int pi = partition(arr, low, high);  // Partition index

 

        // Recursively sort elements before and after partition

        quickSort(arr, low, pi - 1);

        quickSort(arr, pi + 1, high);

    }

}

 

int main() {

    int arr[100], n, i;

 

    // Input number of elements

    printf("Enter number of elements: ");

    scanf("%d", &n);

 

    // Input array elements

    printf("Enter %d elements:\n", n);

    for (i = 0; i < n; i++) {

        scanf("%d", &arr[i]);

    }

 

    // Call Quick Sort

    quickSort(arr, 0, n - 1);

 

    // Display sorted array

    printf("\nSorted array in ascending order:\n");

    for (i = 0; i < n; i++) {

        printf("%d ", arr[i]);

    }

 

    printf("\n");

    return 0;

}

Output

 
INPUT :
Enter number of elements: 6
Enter 6 elements:
10 7 8 9 1 5

OUTPUT 2 :
Sorted array in ascending order:
1 5 7 8 9 10

Explanation

  1. Pivot Selection – The last element is chosen as the pivot.
  2. Partitioning – All elements smaller than the pivot are moved to the left, and all larger elements are moved to the right.
  3. Recursion – Quick Sort is recursively called on the left and right subarrays until all elements are sorted.

 

Algorithm Steps

  1. Pick a pivot element (usually the last one).
  2. Rearrange the array so that elements smaller than pivot are on the left, and greater elements on the right.
  3. Recursively apply the same steps to subarrays.