Published on

The Algorithm Design Manual (3rd) Exercise Solution 'E4-35'

Table of Contents

Introduction

This series is my solutions for algorithm exercises in'The Algorithm Design Manual' 3rd edition.
It's my solutions, not model answers, so if you find some mistakes or more sophisticated solutions, please post in comment area below.

Repository

Here

Exercise 4-35

Question

Let A[1..n]A[1..n] be an array such that the first nnn−√n elements are already sorted (though we know nothing about the remaining elements). Give an algorithm that sorts A in substantially better than nlognn\log{n} steps.

Solution

First We sort n\sqrt{n} elements that's not yet sorted. This costs O(nlogn)O(\sqrt{n}\log{\sqrt{n}}).
Then we merge already sorted part and previously sorted n\sqrt{n} elements using Mergesort-like combination algorithm. This costs O(n)O(n).

n\sqrt{n} dominates logn\log{n}, so n dominates nlognn\log{n}.

The overall time complexity is:

O(n)+O(nlogn)=O(n)+O(nlogn)=O(n)\begin{equation} O(n)+O(\sqrt{n}\log{\sqrt{n}})=O(n)+O(\sqrt{n}\log{n})=O(n) \end{equation}