Skip to main content
Brave Programmer Logo

BraveProgrammer

BraveProgrammer

HomeProjectsBlogsCoursesLessonsAbout

Site footer

BraveProgrammer

Free coding courses, practical tutorials, and real projects from BraveProgrammer. Learn web development with React, Next.js, and TypeScript.

Navigation

  • Home
  • Projects
  • Blogs
  • Courses

Resources

  • About
  • Lessons
  • Teach on BraveProgrammer

© 2026 BraveProgrammer. All rights reserved.

Sorting Algorithms – Qui | C Programming Fundamentals lesson | BraveProgrammer
  1. Courses
  2. /
  3. C Programming Fundamentals

Lesson 35 of 50

·c

Sorting Algorithms – QuickSort & MergeSort

15 mins

Course progress70%

What you'll learn

Keep these ideas in mind as you work through the lesson.

4 points
  • QuickSort is in‑place but needs good pivot selection (e.g., median‑of‑three).
  • MergeSort’s extra memory makes it stable and predictable.
  • Both have O(n log n) average time; recursion depth is O(log n).
  • Tail‑call optimization can reduce stack usage for QuickSort.

Both QuickSort and MergeSort achieve O(n log n) average performance.

  • QuickSort – partition array around a pivot, then recursively sort partitions. In‑place, but worst‑case O(n²) if pivot choices are poor.
  • MergeSort – divide the array, sort each half, then merge. Guarantees O(n log n) but requires O(n) extra space.

Both are classic examples of divide‑and‑conquer.


📚 QuickSort Implementation (Lomuto partition)

void quicksort(int a[], int lo, int hi) {
    if (lo < hi) {
        int p = partition(a, lo, hi);
        quicksort(a, lo, p - 1);
        quicksort(a, p + 1, hi);
    }
}

📚 MergeSort Implementation

void mergesort(int a[], int left, int right) {
    if (left >= right) return;
    int mid = left + (right - left) / 2;
    mergesort(a, left, mid);
    mergesort(a, mid+1, right);
    merge(a, left, mid, right);
}
Make it stickPractice what you've learned1 quiz · 3 practical tests · Optional activities from C Programming FundamentalsBrowse activities
Previous lessonSorting Algorithms – Bubble, Selection, InsertionContinue to lesson 36Searching Algorithms – Linear & Binary SearchBack to C Programming Fundamentals curriculum