100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Quick Sort in C

Learn quick sort in C: partition logic, pivot selection, divide-and-conquer recursion, complete code, output, and O(n log n) average complexity.

Algorithms & Interview PrepIntermediate12 min readJul 7, 2026
Analogies

1. Introduction

Quick sort is a highly efficient, in-place, divide-and-conquer sorting algorithm widely used in practice (it underlies many standard library sort functions). Instead of merging sorted halves like merge sort, quick sort works by selecting a 'pivot' element and partitioning the array so that all elements smaller than the pivot come before it and all elements greater come after it. The pivot then sits in its final sorted position, and the same process is recursively applied to the sub-arrays on either side. On average, quick sort runs in O(n log n) time and requires only O(log n) extra space for recursion, making it faster in practice than merge sort despite sharing the same average-case complexity class.

🏏

Cricket analogy: Quick sort is like seeding an IPL knockout bracket around one benchmark team, the pivot, teams weaker go to one side, stronger to the other, and each side is then re-seeded the same way until the whole bracket is sorted.

2. Syntax

c
void quickSort(int arr[], int low, int high);
int partition(int arr[], int low, int high);

/* Parameters:
   arr  - array of integers to sort in place
   low  - starting index of the current sub-array
   high - ending index of the current sub-array

   Initial call: quickSort(arr, 0, n - 1); */

3. Explanation

This implementation uses the Lomuto partition scheme with the last element as the pivot. partition() picks arr[high] as the pivot, then uses an index i to track the boundary of elements known to be smaller than the pivot. It scans j from low to high - 1; whenever arr[j] < pivot, it increments i and swaps arr[i] with arr[j], growing the 'smaller than pivot' region. After the scan, it swaps arr[i + 1] with arr[high], placing the pivot right after the smaller elements and before the larger ones, and returns i + 1 as the pivot's final sorted index. quickSort() then recursively sorts the sub-array to the left of the pivot (low to pivotIndex - 1) and to the right (pivotIndex + 1 to high).

🏏

Cricket analogy: The Lomuto partition is like a selector using the last player trialed as the benchmark (pivot), keeping an index of confirmed squad members (i) while scanning remaining trialists (j), swapping in anyone better than the benchmark, then slotting the benchmark player right after the confirmed group.

Worked trace on [10, 7, 8, 9, 1, 5] with pivot = arr[high] = 5: i starts at -1. j=0: arr[0]=10, not < 5, skip. j=1: arr[1]=7, not < 5, skip. j=2: arr[2]=8, not < 5, skip. j=3: arr[3]=9, not < 5, skip. j=4: arr[4]=1, 1 < 5, so i becomes 0, swap arr[0] and arr[4] -> [1,7,8,9,10,5]. Loop ends; swap arr[i+1]=arr[1] with arr[high]=arr[5] -> [1,5,8,9,10,7]. Pivot 5 is now at index 1, its correct sorted position, with quickSort then recursing on [1] (left, already sorted) and [8,9,10,7] (right, indices 2-5).

🏏

Cricket analogy: Tracing quick sort on scores [10,7,8,9,1,5] with pivot 5 is like a selector scanning five trialists' fitness scores against a benchmark of 5, finding only the score of 1 beats it, swapping it forward, then placing the benchmark 5 right after it, leaving [1,5,8,9,10,7] with 5 correctly seated at index 1.

4. Example

c
#include <stdio.h>

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

int partition(int arr[], int low, int high) {
    int pivot = arr[high];
    int i = low - 1;

    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;
}

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

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) printf("%d ", arr[i]);
    printf("\n");
}

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

    quickSort(arr, 0, n - 1);
    printArray(arr, n);
    return 0;
}

5. Output

text
1 5 7 8 9 10

6. Key Takeaways

  • Average-case time complexity is O(n log n), which is what makes quick sort practical for general-purpose use.
  • Worst-case time complexity is O(n^2), which occurs when the pivot is repeatedly the smallest or largest element (e.g., an already-sorted array with last-element pivoting).
  • Quick sort is an in-place algorithm requiring only O(log n) extra space for the recursion stack (average case).
  • It is not a stable sort by default, since the partition step can reorder equal elements.
  • Randomized or median-of-three pivot selection helps avoid the O(n^2) worst case on already-sorted input.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#QuickSortInC#Quick#Sort#Syntax#Explanation#Algorithms#StudyNotes#SkillVeris

Frequently Asked Questions

21 categories · pick one to explore

Where can I get free study notes for programming and tech subjects?
SkillVeris offers completely free study notes covering programming and tech subjects, with no signup fees or paywalls. The notes are structured by course and topic, written for quick understanding, and enriched with the Learn Through Hobbies analogy method, so you can revise concepts through cricket, music, gaming, cooking and more.
Are SkillVeris study notes good for exam revision?
Yes, the study notes are designed for efficient revision: each topic answers its heading immediately, keeps explanations concise, and links to related glossary terms and cheat sheets. Students preparing for university exams or certification tests use them as quick revision notes because they distil concepts without the padding of full textbooks.
What subjects do the free study notes cover?
The study notes span the platform's main domains, including AI and machine learning, Python and programming, web development, DevOps, cloud, security and databases. Coverage mirrors the 37 live courses, so notes exist for the topics you are actually studying, and new note sets are added as courses launch.
How are SkillVeris study notes different from regular textbooks?
The notes are answer-first, concise and free, whereas textbooks are long and often expensive. Each section explains one concept directly, then reinforces it through selectable hobby analogies like cricket or cooking. Notes also cross-link to the glossary, blog and cheat sheets, letting you jump to related material instantly instead of flipping pages.
Can I use the developer study material without creating an account?
The study notes are free to access, and SkillVeris does not charge anything for its developer study material at any point. Browsing notes is straightforward from the Study Notes section, and if you want progress tracking, certificates and AI Mentor conversations tied to your learning, a free account unlocks those extras.
Do the study notes explain concepts with analogies?
Yes, this is a signature SkillVeris feature. Study notes use the Learn Through Hobbies method, explaining technical concepts through analogies from twelve domains including cricket, music, gaming, photography, travel, movies, fitness, chess, cooking, finance, business and sports. You can switch the analogy domain instantly to whichever hobby makes the concept click.
Are the revision notes suitable for last-minute exam preparation?
Yes, revision notes on SkillVeris work well for last-minute preparation because every section states the answer in its first sentences, so skimming is genuinely effective. Pair them with the relevant cheat sheet for formulas and syntax, and use the glossary for any unfamiliar term you meet while cramming.
Is there free study material for AI and machine learning?
Yes, SkillVeris provides free study notes across its AI and ML catalogue, covering Python for AI, deep learning frameworks like PyTorch and TensorFlow, Hugging Face Transformers, Large Language Models, RAG, AI agents and MLOps. All of it is free, making it a strong resource for Indian students and global learners alike.
Can beginners understand the study notes, or are they for experts?
Beginners can absolutely use them. The notes are written in plain language, define terms as they appear, and lean on hobby analogies to make abstract ideas concrete. Difficulty scales with the underlying course level, so beginner-course notes stay gentle while advanced-course notes go deeper, and the glossary supports you throughout.
How do study notes connect with SkillVeris courses?
Study notes are organised by course and topic, so they map directly to the structured courses and their 24–40-lesson curriculum. Many learners study a lesson first, then use the matching notes for revision before module assessments and the final exam, where 80 percent is required to pass and earn the certificate.
Are there study notes for Python specifically?
Yes, Python is well covered through notes tied to the Python-focused courses, including Python for AI and ML. Topics span fundamentals through applied machine learning usage. You can reinforce the notes with Python practice in Code Lab, which runs code in your browser with no installation required.
Do the study notes include code examples?
Yes, study notes include code examples wherever a concept is best shown in code, alongside explanations, key points and analogies. Reading a snippet in the notes and then reproducing it yourself in Code Lab is an effective loop, since Code Lab lets you run code in the browser across six languages.
How often is new study material added to SkillVeris?
Study material grows alongside the course catalogue. Whenever new courses join the platform's 37 live courses, matching study notes, glossary entries and cheat sheets are added so the resources stay in sync. Existing notes are also refined over time, so it is worth revisiting topics you studied earlier.
Can I use SkillVeris notes to prepare for technical interviews?
Yes, the notes make excellent interview revision because they compress each concept into direct, answer-first explanations, which mirrors how you should answer interview questions. Combine them with the SkillVeris interview questions feature, which includes readiness scoring, to test whether your revision has actually made you interview-ready.
Are the study notes mobile-friendly for studying on the go?
Yes, the study notes are built to load fast and read comfortably on mobile devices, so you can revise during a commute or between classes. Sections are short and answer-first, which suits small screens, and analogy switching works on mobile too, letting you study anywhere without carrying books.
What is the difference between study notes and cheat sheets?
Study notes explain concepts in depth with context, examples and analogies, making them ideal for learning and revision. Cheat sheets are compact quick-reference summaries of syntax, commands and key facts, ideal once you already understand a topic. Most learners study the notes first, then keep the cheat sheet handy while coding.
Do study notes help if I am stuck on a course lesson?
Yes, reading the matching study notes often clarifies a lesson because the same concept is explained from a different angle, frequently with a different analogy. If you are still stuck, ask the AI Mentor, which answers 24/7 at Quick, Detailed or Deep-dive depth until the idea genuinely makes sense.
Is there free study material for DevOps and cloud topics?
Yes, SkillVeris carries free study notes for DevOps and cloud topics as part of its coverage across 37 live courses. The material suits learners following the DevOps Engineer or Cloud Engineer paths, and it links to related glossary terms and cheat sheets so you can revise the whole toolchain in one place.
Can school or college students in India use these notes for projects?
Yes, students across India and worldwide use SkillVeris notes for coursework, projects and exam preparation, and everything is free, which matters for student budgets. The notes explain concepts clearly enough to cite in project reports, and Code Lab lets you prototype the project code directly in your browser.
How should I combine study notes with other SkillVeris resources?
A proven loop: learn from a course lesson, revise with the matching study notes, look up unfamiliar terms in the glossary, keep the cheat sheet open while practising in Code Lab, and quiz yourself with interview questions. The AI Mentor fills any remaining gaps 24/7, at whatever depth you need.

What Learners Say

Real journeys from the SkillVeris community — swipe for more.

SkillVeris taught me Python through Cricket. Now I’m building real projects and feeling confident!
Arjun S. · B.Tech Student
The best platform for hobby-based learning. Concepts finally stick.
Priya R. · Data Analyst
I went from zero coding to a portfolio of projects — all by learning through my love for gaming. Landed my first internship!
Kabir M. · CS Undergraduate
Trending Topics50 popular tags — tap to explore
Trending CoursesAll 37 free courses — tap to browse