Skip to main content

Command Palette

Search for a command to run...

[Algorithm] Merge Sort with Divide and Conquer Algorithm

Published
4 min read

※ I'm neither a native speaker nor an expert. I'm just a noob student who wants to develop the literacy in English and software knowledge. If you find any wrong content or awkward expressions, please feel free to let me know. Thank you!


There are many methods for sorting data efficiently, called 'sort algorithm'. In this section, merge sort will be dealt with. This algorithm achieves sorting things with the time complexity O(nlogn).

Divide and Conquer?

The basic idea of the 'divide and conquer' algorithm is breaking a whole complex problem into sub-problems that can be solved more easily. This involves three parts.

  1. Divide the given problem into smaller problems until it can be solvable.

  2. Conquer (or solve) the sub-problems.

  3. Combine the answers to each sub-problem and get the solution to the original problem.


The basic principle of sorting

Assume that there is a 'target data' to be sorted. In merge sort, the first step is dividing the target into two pieces until the size of the piece becomes one. To get a grasp on this easily, let's take an example. Suppose there is an array following.

8 6 1 5 9 3 4 5

First, divide into the 8 segments.

8 6 1 5 / 9 3 4 5

8 6 / 1 5 / 9 3 / 4 5

8 / 6 / 1 / 5 / 9 / 3 / 4 / 5

Then, the neighboring two parts get merged by the comparison between the first elements of each part, as shown below.

// First step
6 8 / 1 5 / 3 9 / 4 5

// Second step
// Given the first two parts, 
6 8 / 1 5
// compare 6 and 1, which are the first elements of each parts.
6 8 / 5
1
// Then, again, compare 6 and 5, which are the first elements of each parts.
6 8 
1 5
// Now, the remaining elements will follow.
1 5 6 8
// Repeat this
1 5 6 8 / 3 4 5 9

// Third step
1 3 4 5 6 7 8 9

How to write the code actually

Since divide and conquer is a recursive method, the sort function is also written as recursively. In the dividing step, we separate a whole data array into two intervals.

void merge_sort(int* target, int start, int end)
{
    // temporary memory for copying data
    int* copy = new int[end - start + 1];
    merge_inner(target, copy, start, end);
}

// sort function
void merge_inner(int* target, int* copy, int start, int end)
{
    // There must be 'end point' of recursive process.
    if (start == end) return;

    // Divide the interval into two parts.
    int middle = (start + end) >> 1;    
    merge_inner(target, copy, start, middle);
    merge_inner(target, copy, middle + 1, end);
    // After this, each two parts will be sorted.

Next, the conquering step will merge each two separate parts into one.

    // Copy the original array first,
    // because we need to store temporarily the current state of data
    for (int i = start; i <= end; ++i)
    {
        copy[i] = target[i];
    }

    // Sort (Conquer and Combine)
    int left_index = start, right_index = middle + 1;
    int target_index = start;
    while (left_index <= middle && right_index <= end)
    {
        // ascending sorting 
        // This part could be changed depending on 'how you want to sort'
        if (compare(copy[left_index], copy[right_index]))
        {
            target[target_index++] = copy[left_index++];
        }
        else
        {
            target[target_index++] = copy[right_index++];
        }
    }

    while (left_index <= middle)
    {
        target[target_index++] = copy[left_index++];
    }
    while (right_index <= end)
    {
        target[target_index++] = copy[right_index++];
    }
}

bool compare(int a, int b)
{
    return a <= b;
}

As you might noticed, the copied data is required in merge sort. Therefore, the space complexity is O(n).

Divide and conquer algorithm is used in other various problems, such as quick sort, multiplication, and FFT. There will be more chances to take a look at divide and conquer algorithm.

Edited by Sang Hyeok Park

More from this blog

[ZSH] tree 사용하기

들어가며 큰 규모의 프로젝트를 출시한 뒤, 후일을 위해서 더 늦기 전에 파일 정리 및 문서화를 진행해야했다. 문서화 작업을 하는 중에 기왕 정리하는 거 파일 구조를 이쁘게 트리 구조로 나열하여 코멘트를 달면 나중에 보더라도 이해하기 더 쉬울 것 같았다. 어떻게 해야 간지나는 트리 구조를 만들 수 있을까 방법을 찾다보니 역시나 파일 구조를 트리로 이쁘게 출력해주는 커맨드 툴이 존재했다. tree 커맨드에 대해서 알아보고 알짜배기 내용만 정리했다....

Feb 21, 20242 min read

[Next.js] parallel routes & intercepting routes

트위터 로그인 모달창을 만들어보며 넥스트의 parallel routes 와 intercepting routes 을 학습한 내용을 정리해보았습니다. 트위터 로그인 창을 확인해봅시다. 루트 디렉토리 화면을 배경으로 i/flow/login 페이지가 동시에 표시되고 있습니다. 저는 app router 를 학습하기 전까지는 createPortal 을 사용하여 포탈 영역에 로그인 컴포넌트를 띄우는 방식을 사용했었습니다. const NoLogin =()=...

Feb 1, 20244 min read

C/C++ 이진 트리(binary tree) 개요 및 구현(1)

개요 트리는 노드들이 나무 가지처럼 연결된 비선형 계층적 자료구조이다. 하위 트리가 존재하고, 그 노드에 또 하위 트리가 존재하는 자료구조 이다. 트리의 맨 위에 있는 루트 노드가 존재한다. 우리가 알아볼 트리는 이진 트리이다. 이진 트리는 자식 노드(부모로부터 아래로 이어진 노드)가 2개 이하인 구조를 말한다. 트리의 사용 사례로는 다음과 같다 계층 적 데이터 저장(파일,폴더) 효율적인 검색 속도 힙 데이터 베이스의 인덱싱 트리에 ...

Jan 31, 20244 min read

[React] Server component (RSC)

React.js 18 에 도입된 리액트 서버 컴포넌트는 서버에서 동작하는 리액트 컴포넌트를 의미합니다. Next가 권장하는 라우팅 방식인 app router의 기반이 되는 컴포넌트이기 때문에 app router 를 이해하기 위해서는 server component 에 대한 이해가 필요합니다. server component 리액트는 클라이언트단만을 컴포넌트화하는 대신, server component라는 개념을 통해 서버 영역을 컴포넌트화합니다. ...

Jan 29, 20243 min read

Flutter, JavaScript

42 posts