Docsity

Sorting - Algorithm - Study Notes, Study notes of Algorithms and Programming

Partial preview of the text

Download Sorting - Algorithm - Study Notes and more Study notes Algorithms and Programming in PDF only on Docsity!

Design and Analysis of Algorithms

Chapter 4

Sorting

For the next series of lectures, we will focus on sorting. There a number of reasons for sorting. Here are a few important ones. Procedures for sorting are parts of many large software systems. Design of efficient sorting algorithms is necessary to achieve overall efficiency of these systems.

Sorting is well studied problem from the analysis point of view. Sorting is one of the few problems where provable lower bounds exist on how fast we can sort. In sorting, we are given an array A[1..n] of n numbers We are to reorder these elements into increasing (or decreasing) order.

More generally, A is an array of objects and we sort them based on one of the attributes - the key value. The key value need not be a number. It can be any object from a totally ordered domain. Totally ordered domain means that for any two elements of the domain, x and y, either x < y, x = y or x > y.

4.1 Slow Sorting Algorithms

There are a number of well-known slow O(n^2 ) sorting algorithms. These include the following:

Bubble sort: Scan the array. Whenever two consecutive items are found that are out of order, swap them. Repeat until all consecutive items are in order.

Insertion sort: Assume that A[1..i − 1 ] have already been sorted. Insert A[i] into its proper position in this sub array. Create this position by shifting all larger elements to the right.

Selection sort: Assume that A[1..i − 1 ] contain the i − 1 smallest elements in sorted order. Find the smallest element in A[i..n] Swap it with A[i].

These algorithms are easy to implement. But they run in Θ(n^2 ) time in the worst case.

4.2. SORTING IN O(N LOG N) TIME 41

to nodes involves simple arithmetic operations:

left(i) : returns 2i, index of left child of node i. right(i) : returns 2i + 1 , the right child. parent(i) : returns bi/2c, the parent of i.

The root is at position 1 of the array.

4.2.2 Heapsort Algorithm

We build a max heap out of the given array of numbers A[1..n]. We repeatedly extract the the maximum item from the heap. Once the max item is removed, we are left with a hole at the root. To fix this, we will replace it with the last leaf in tree. But now the heap order will very likely be destroyed. We will apply a heapify procedure to the root to restore the heap. Figure 4.2 shows an array being sorted.

HEAPSORT( array A, int n) 1 BUILD-HEAP(A, n) 2 m ← n 3 while (m ≥ 2 ) 4 do SWAP(A[ 1 ], A[m]) 5 m ← m − 1 6 HEAPIFY(A, 1, m)

42 CHAPTER 4. SORTING

87 57 44 12 15 19 23

0 1 2 3 4 5 6 7

2412 3115

2157

1919

1644

6823

1387

0 1 2 3 4 5 6 7

2412 3115

2157

1919

1644

6823

1387

(^2357 44 12 15 )

0 1 2 3 4 5 6 7

2412 3115

2157 1919

1644

6823

1387

sorted (^) ⇒

2357 44 12 15 1987

(^01 2 3 4 5 6 )

2412 3115

2157 1919

1644

6823

sorted

heap violated

57 2344 12 15 1987

(^01 2 3 4 5 6 )

2412 3115

2157

1919

(^68231644)

sorted (^) ⇒

57 2344 12 15 1987

(^01 2 3 4 5 6 )

2412 3115

2157

1919

(^68231644)

sorted (^) ⇒

19 2344 12 155787

(^01 2 3 4 5 6 )

2412 3115 2157

1919 (^68231644)

sorted (^) ⇒

44 231912 155787

(^01 2 3 4 5 6 )

2412 3115

1919

1644 6823

sorted (^) ⇒

44 231912 155787

(^01 2 3 4 5 6 )

2412 3115

1919

1644 6823

sorted (^) ⇒

(^15 )

(^01 2 3 4 5 6 )

2412

3115 1919 1644

6823

sorted (^) ⇒

2315 1912445787

0 1 2 3 4 5 6 7

2412

3115 1919

6823

sorted (^) ⇒

2315 1912 445787

0 1 2 3 4 5 6 7

2412

3115 1919

6823

sorted (^) ⇒

(^12 15 19 )

0 1 2 3 4 5 6 7

2412 3115 1919 6823

sorted (^) ⇒

19 151223445787

0 1 2 3 4 5 6 7

3115 2412

1919

sorted (^) ⇒

19 151223445787

0 1 2 3 4 5 6 7

3115 2412

1919

sorted (^) ⇒

15 1219 23445787

0 1 2 3 4 5 6 7

2412

3115

sorted (^) ⇒

12 15 19 23445787

0 1 2 3 4 5 6 7

sorted

Figure 4.2: Example of heap sort

44 CHAPTER 4. SORTING

Here is the code. Since we will work with the entire array, the parameter m for Heapify, which indicates the current heap size will be equal to n, the size of array A, in all the calls.

BUILDHEAP( array A, int n) 1 for i ← n/2 downto 1 2 do 3 HEAPIFY(A, i, n)

4.2.6 Analysis of BuildHeap

For convenience, we will assume n = 2 h+^1 − 1 where h is the height of tree. The heap is a left-complete binary tree. Thus at each level j, j < h, there are 2 j^ nodes in the tree. At level h, there will be 2 h^ or less nodes. How much work does buildHeap carry out? Consider the heap in Figure 4.3:

3

2

1

0 0

1

0 0

2

1

0 0

1

0 0

3 x 1

1 x 4

2 x 2

0 x 8

Figure 4.3: Total work performed in buildheap

At the bottom most level, there are 2 h^ nodes but we do not heapify these. At the next level up, there are 2 h−^1 nodes and each might shift down 1. In general, at level j, there are 2 h−j^ nodes and each may shift down j levels.

So, if count from bottom to top, level-by-level, the total time is

T (n) =

∑^ h

j= 0

j2h−j^ =

∑^ h

j= 0

j

2 h 2 j

We can factor out the 2 h^ term:

T (n) = 2 h

∑h

j= 0

j 2 j

4.2. SORTING IN O(N LOG N) TIME 45

How do we solve this sum? Recall the geometric series, for any constant x < 1

∑^ ∞

j= 0

xj^ =

1 − x

Take the derivative with respect to x and multiply by x

∑^ ∞

j= 0

jxj−^1 =

( 1 − x)^2

∑^ ∞

j= 0

jxj^ =

x ( 1 − x)^2

We plug x = 1/2 and we have the desired formula:

∑^ ∞

j= 0

j 2 j^

( 1 − (1/2))^2

In our case, we have a bounded sum, but since we the infinite series is bounded, we can use it as an easy approximation:

T (n) = 2 h

∑h

j= 0

j 2 j

≤ 2 h

∑^ ∞

j= 0

j 2 j

≤ 2 h^ · 2 = 2 h+^1

Recall that n = 2 h+^1 − 1. Therefore

T (n) ≤ n + 1 ∈ O(n)

The algorithm takes at least Ω(n) time since it must access every element at once. So the total time for BuildHeap is Θ(n).

BuildHeap is a relatively complex algorithm. Yet, the analysis yield that it takes Θ(n) time. An intuitive way to describe why it is so is to observe an important fact about binary trees The fact is that the vast majority of the nodes are at the lowest level of the tree. For example, in a complete binary tree of height h, there is a total of n ≈ 2 h+^1 nodes.

The number of nodes at the bottom three levels alone is

2 h^ + 2 h−^1 + 2 h−^2 =

n 2

n 4

n 8

7n 8

= 0.875n

Almost 90% of the nodes of a complete binary tree reside in the 3 lowest levels. Thus, algorithms that operate on trees should be efficient (as BuildHeap is) on the bottom-most levels since that is where most of the weight of the tree resides.

4.3. QUICKSORT 47

or equal to x A[s..r] contains elements whose values are currently unknown.

PARTITION( array A, int p, int r) 1 x ← A[p] 2 q ← p 3 for s ← p + 1 to r 4 do if (A[s] < x) 5 then q ← q + 1 6 swap A[q] with A[s] 7 swap A[p] with A[q] 8 return q

Figure 4.4 shows the execution trace partition algorithm.

p 5 8 6 4 7 3 1

r

q s

p 5 3 8 6 4 7 3 1

r

q (^) s

p 5 3 8 6 4 7 3 1

r

q (^) s

p 5 3 8 6 7 3 1

r

q (^) s

p 5 3 4 6 8 7 3 1

r

q s

p 5 3 4 6 8 7 1

r

q s

p (^) r

q (^) s

p (^) r

q s

p r

q s

Figure 4.4: Trace of partitioning algorithm

4.3.2 Quick Sort Example

The Figure 4.5 trace out the quick sort algorithm. The first partition is done using the last element, 10 , of the array. The left portion are then partitioned about 5 while the right portion is partitioned about 13. Notice that 10 is now at its final position in the eventual sorted order. The process repeats as the algorithm recursively partitions the array eventually sorting it.

48 CHAPTER 4. SORTING

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 11 22 44 33 55 88 66 77 99 1010 1212 1111 1313 1414 1515 1717 1616 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 11 22 44 33 55 88 66 77 99 1010 1212 1111 1313 1414 1515 1717 1616 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 11 22 44 33 55 88 66 77 99 1010 1212 1111 1313 1414 1515 1717 1616 11 22 33 44 55 88 66 77 99 1010 1111 1212 1313 1414 1515 1616 1717 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 11 22 44 33 55 88 66 77 99 1010 1212 1111 1313 1414 1515 1717 1616 11 22 33 44 55 88 66 77 99 1010 1111 1212 1313 1414 1515 1616 1717 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717 ⇓

777 666 121212 333 111111 888 777 111 151515 131313 171717 555 161616 141414 999 444 101010 77 66 44 33 99 88 22 11 55 1010 1717 1515 1616 1414 1111 1212 1313 11 22 44 33 55 88 66 77 99 1010 1212 1111 1313 1414 1515 1717 1616 11 22 33 44 55 88 66 77 99 1010 1111 1212 1313 1414 1515 1616 1717 11 22 33 44 55 66 77 88 99 1010 1111 1212 1313 1414 1515 1616 1717

Figure 4.5: Example of quick sort

50 CHAPTER 4. SORTING

This depends on the value of q. To get the worst case, we maximize over all possible values of q. Putting is together, we get the recurrence

T (n) =

1 if n ≤ 1 max 1 ≤q≤n

(T (q − 1 ) + T (n − q) + n) otherwise

Recurrences that have max’s and min’s embedded in them are very messy to solve. The key is determining which value of q gives the maximum. (A rule of thumb of algorithm analysis is that the worst cases tends to happen either at the extremes or in the middle. So I would plug in the value q = 1 , q = n, and q = n/2 and work each out.) In this case, the worst case happens at either of the extremes. If we expand the recurrence for q = 1 , we get:

T (n) ≤ T ( 0 ) + T (n − 1 ) + n = 1 + T (n − 1 ) + n = T (n − 1 ) + (n + 1 ) = T (n − 2 ) + n + (n + 1 ) = T (n − 3 ) + (n − 1 ) + n + (n + 1 ) = T (n − 4 ) + (n − 2 ) + (n − 1 ) + n + (n + 1 )

= T (n − k) +

∑^ k−^2

i=− 1

(n − i)

For the basis T ( 1 ) = 1 we set k = n − 1 and get

T (n) ≤ T ( 1 ) +

∑^ n−^3

i=− 1

(n − i)

= 1 + ( 3 + 4 + 5 + · · · + (n − 1 ) + n + (n + 1 ))

n∑+ 1

i= 1

i =

(n + 1 )(n + 2 ) 2

∈ Θ(n^2 )

4.3.5 Average-case Analysis of Quicksort

We will now show that in the average case, quicksort runs in Θ(n log n) time. Recall that when we talked about average case at the beginning of the semester, we said that it depends on some assumption about the distribution of inputs. However, in the case of quicksort, the analysis does not depend on the distribution of input at all. It only depends upon the random choices of pivots that the algorithm makes. This is good, because it means that the analysis of the algorithm’s performance is the same for all inputs. In this case the average is computed over all possible random choices that the algorithm might make for the choice of the pivot index in the second step of the QuickSort procedure above.

To analyze the average running time, we let T (n) denote the average running time of QuickSort on a list of size n. It will simplify the analysis to assume that all of the elements are distinct. The algorithm has n

4.3. QUICKSORT 51

random choices for the pivot element, and each choice has an equal probability of 1/n of occuring. So we can modify the above recurrence to compute an average rather than a max, giving:

T (n) =

1 if n ≤ 1 1 n

∑n q= 1 (T^ (q^ −^1 ) +^ T^ (n^ −^ q) +^ n)^ otherwise

The time T (n) is the weighted sum of the times taken for various choices of q. I.e.,

T (n) =

[ 1

n

(T ( 0 ) + T (n − 1 ) + n)

n

(T ( 1 ) + T (n − 2 ) + n)

n

(T ( 2 ) + T (n − 3 ) + n)

  • · · · +

n

(T (n − 1 ) + T ( 0 ) + n)

]

We have not seen such a recurrence before. To solve it, expansion is possible but it is rather tricky. We will attempt a constructive induction to solve it. We know that we want a Θ(n log n). Let us assume that T (n) ≤ cn log n for n ≥ 2 where c is a constant.

For the base case n = 2 we have

T (n) =

∑^2

q= 1

(T (q − 1 ) + T ( 2 − q) + 2 )

[
(T ( 0 ) + T ( 1 ) + 2 ) + (T ( 1 ) + T ( 0 ) + 2 )
]

We want this to be at most c2 log 2 , i.e.,

T ( 2 ) ≤ c2 log 2

or

4 ≤ c2 log 2

therefore

c ≥ 4/( 2 log 2 ) ≈ 2.88.

For the induction step, we assume that n ≥ 3 and The induction hypothesis is that for any n′^ < n, we have T (n′) ≤ cn′^ log n′. We want to prove that it is true for T (n). By expanding T (n) and moving the

4.3. QUICKSORT 53

The function f(x) = xln x is monotonically increasing, and so

S(n) =

n∑− 1

q= 2

(cqln q) ≤

∫ (^) n

2

xln x dx (4.1)

We can integrate this by parts: (^) ∫ n

2

xln x dx =

x^2 2

ln x −

x^2 4

n x= 2

∫ (^) n

2

xln x dx =

x^2 2

ln x −

x^2 4

n x= 2

=

(n 2

2

ln n −

n^2 4

− ( 2 ln 2 − 1 )

n^2 2

ln n −

n^2 4 We thus have

S(n) =

n∑− 1

q= 2

(cqln q) ≤

n^2 2

ln n −

n^2 4

Plug this back into the expression for T (n) to get

T (n) =

2c n

(n 2

2

ln n −

n^2 4

  • n +

n

T (n) =

2c n

(n 2

2

ln n −

n^2 4

  • n +

n = cnln n −

cn 2

  • n +

n = cnln n + n

c 2

n

T (n) = cnln n + n

c 2

n To finish the proof,we want all of this to be at most cnln n. For this to happen, we will need to select c such that

n

c 2

n

If we select c = 3 , and use the fact that n ≥ 3 we get

n

c 2

n

n

n 2 ≤ 1 −

From the basis case we had c ≥ 2.88. Choosing c = 3 satisfies all the constraints. Thus T (n) = 3nln n ∈ Θ(n log n).

54 CHAPTER 4. SORTING

4.4 In-place, Stable Sorting

An in-place sorting algorithm is one that uses no additional array for storage. A sorting algorithm is stable if duplicate elements remain in the same relative position after sorting.

∣ 3 ′^
∣ 5 ′^

∣ 3 ′′^ unsorted

1

∣ 3 ′^
∣ 3 ′′^
∣ 5 ′^

∣ (^9) stable sort

1

∣ 3 ′^
∣ 3 ′′^
∣ 5 ′^

∣ (^9) unstable

Bubble sort, insertion sort and selection sort are in-place sorting algorithms. Bubble sort and insertion sort can be implemented as stable algorithms but selection sort cannot (without significant modifications). Mergesort is a stable algorithm but not an in-place algorithm. It requires extra array storage. Quicksort is not stable but is an in-place algorithm. Heapsort is an in-place algorithm but is not stable.

4.5 Lower Bounds for Sorting

The best we have seen so far is O(n log n) algorithms for sorting. Is it possible to do better than O(n log n)? If a sorting algorithm is solely based on comparison of keys in the array then it is impossible to sort more efficiently than Ω(n log n) time. All algorithms we have seen so far are comparison-based sorting algorithms.

Consider sorting three numbers a 1 , a 2 , a 3. There are 3! = 6 possible combinations:

(a 1 , a 2 , a 3 ), (a 1 , a 3 , a 2 ) , (a 3 , a 2 , a 1 ) (a 3 , a 1 , a 2 ), (a 2 , a 1 , a 3 ) , (a 2 , a 3 , a 1 )

One of these permutations leads to the numbers in sorted order.

The comparison based algorithm defines a decision tree. Here is the tree for the three numbers.