FirstHack Learn
Log in Sign up free
Lessons in this course 0/6 All courses Algorithms and Complexity

CSE

Progress0 / 6 lessons
  1. 1. Big-O without hand-waving
  2. 2. Searching: linear and binary
  3. 3. Bubble, selection and insertion sort
  4. 4. Merge sort and quick sort
  5. 5. Recursion and how to reason about it
  6. 6. Greedy versus dynamic programming

Courses › Algorithms and Complexity

Merge sort and quick sort

Divide and conquer, the recurrences solved properly, and why quick sort is the default.

13 min read · Lesson 4 of 6 · Pro

The idea both share

Sorting n elements costs about n^2. Sorting two halves costs 2 x (n/2)^2 = n^2/2 - half the work. Split again and it halves again. That is divide and conquer: break the problem, solve the pieces, combine.

Merge sort and quick sort differ in where the work happens. Merge sort splits carelessly and combines carefully. Quick sort splits carefully and combines for free.

Merge sort

C++
#include <iostream>
using namespace std;

void merge(int a[], int left, int mid, int right, int temp[]) {
    int i = left, j = mid + 1, k = left;
The rest of this lesson is Pro

The free lessons of Algorithms and Complexity finish what they start — read those first if you have not. This one goes further, and it is part of the paid half.

A pass opens the paid lessons of every course, the mock test papers and the company-wise series. It ends on its own date; nothing renews by itself.

Get a pass — from ₹29 for 7 days

Already bought one? Log in.