C PROGRAMMING PROGRAM • ARRAYS, SEARCHING & SORTING

Sort an Array Using Quick Sort

Learn how to sort an array using quick sort using a clear C program.

AdvancedQuick sortPartitionRecursion

PROBLEM UNDERSTANDING

Input and expected output

Sample input
7
10 7 8 9 1 5 3
Sample output
1 3 5 7 8 9 10

COMPLETE C PROGRAM

Complete C implementation

quick-sort.c
Open in compiler
#include <stdio.h>

int partition(int values[], int low, int high)
{
    int pivot = values[high], smaller = low - 1;
    for (int index = low; index < high; index++) {
        if (values[index] <= pivot) {
            smaller++;
            int temporary = values[smaller]; values[smaller] = values[index]; values[index] = temporary;
        }
    }
    int temporary = values[smaller + 1]; values[smaller + 1] = values[high]; values[high] = temporary;
    return smaller + 1;
}

void quickSort(int values[], int low, int high)
{
    if (low < high) {
        int pivot = partition(values, low, high);
        quickSort(values, low, pivot - 1);
        quickSort(values, pivot + 1, high);
    }
}

int main(void)
{
    int size, values[100];

    scanf("%d", &size);
    if (size < 1 || size > 100) return 1;
    for (int index = 0; index < size; index++) scanf("%d", &values[index]);
    quickSort(values, 0, size - 1);
    for (int index = 0; index < size; index++) printf("%d%c", values[index], index == size - 1 ? '\n' : ' ');
    return 0;
}

GUIDED CODE TOUR • NOT LIVE EXECUTION

Study the program line by line

Use the real compiler button above to run and debug with different inputs.

CURRENT STEP

Select Start to walk through the important lines.

SELECTED LINE

No line selected

EXPECTED OUTPUT FOR THE SAMPLE

1 3 5 7 8 9 10
0%Step 0 of 0

PROGRAM EXPLANATION

Algorithm and explanation

  1. Read the required input values.
  2. Partition around a pivot and recursively sort the values on both sides.
  3. Display the computed result.

Partition around a pivot and recursively sort the values on both sides.

EFFICIENCY

Time and space complexity

Time complexity

O(n log n) average

Auxiliary space

O(log n) average

DEBUGGING CHECKLIST

Common mistakes

Check this

Use the correct format specifier for every variable.

Check this

Initialize variables before using their values.

Check this

Check braces, semicolons and input order carefully.

Try it yourself

Practice: Run the program with the sample input, predict its output, and then test one boundary case of your own.