SORTTING IN LINEAR TIME - Radix Sort

15
RADIX SORT

Transcript of SORTTING IN LINEAR TIME - Radix Sort

Page 1: SORTTING IN LINEAR TIME - Radix Sort

RADIX SORT

Page 2: SORTTING IN LINEAR TIME - Radix Sort

RADIX SORT

• Radix sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value.

• A positional notation is required, but because integers can represent strings of characters (e.g., names or dates), radix sort is not limited to integers

Page 3: SORTTING IN LINEAR TIME - Radix Sort

PSEUDOCODE

• RADIX_SORT (A, d)

1. for i = 1 to d

2. Stable_Sort (A) on digit i

Page 4: SORTTING IN LINEAR TIME - Radix Sort

EXAMPLE

• Let’s sort the following array using radix sort:

A[10] =64 8 216 512 27 729 0 1 343 125

Page 5: SORTTING IN LINEAR TIME - Radix Sort

PASS 1

A[10] =8 216 512 27 729 0 1 343 12564

Page 6: SORTTING IN LINEAR TIME - Radix Sort

PASS 1

Sorted Array after pass 1 (LSD)

A[10] =1 512 343 64 125 216 27 8 7290

Page 7: SORTTING IN LINEAR TIME - Radix Sort

PASS 2

A[10] =01 512 343 64 125 216 27 08 72900

Page 8: SORTTING IN LINEAR TIME - Radix Sort

PASS 2

Sorted Array after pass 2 :

A[10] =01 08 512 216 125 27 729 343 6400

Page 9: SORTTING IN LINEAR TIME - Radix Sort

PASS 3

A[10] =001 008 512 216 125 027 729 343 064000

Page 10: SORTTING IN LINEAR TIME - Radix Sort

PASS 3

Sorted Array after pass 3 :

A[10] =001 008 027 064 125 216 343 512 729000

Page 11: SORTTING IN LINEAR TIME - Radix Sort

ANALYSIS

• Assume that we use counting sort as the intermediate sort.

• Ө(n+k) per pass (digits in the range 0,….,k)

• d passes

• Total = Ө(d(n+k))

• If k=O(n), Time = Ө(dn)

Page 12: SORTTING IN LINEAR TIME - Radix Sort

Can we prove it will work?

• Basis: If d = 1, there’s only one digit, so sorting on that digit sorts the array.

• Inductive Step:

• Assume lower-order digits {j: j<i} are sorted

• Show that sorting next digit i leaves array correctly sorted

• If two digits at position i are different, ordering numbers by that digit is correct.

• If they are the same, numbers are already sorted on the lower-order digits. Since we use a stable sort, the numbers stay in the right order

Page 13: SORTTING IN LINEAR TIME - Radix Sort

How to break each key into digits? (Lemma 8.4)

• n keys

• b bits/key

• Break into r-bit digits (r ≤ b). Have d =𝒃

𝒓

• Use counting sort, k = 2𝑟-1

Page 14: SORTTING IN LINEAR TIME - Radix Sort

EXAMPLE

• 32- bit keys, 8- bit digits.

• b = 32, r = 8, d = 32/8 = 4

• k = 28 – 1 = 255

• Time = Ө(b/r(n + 2𝑟))

Page 15: SORTTING IN LINEAR TIME - Radix Sort

• If b < lgn

(n + 2𝑟) = Ө(n). Thus, choosing r = b yields an optimal running time of (b/b(n + 2𝑏)) = Ө(n)

• If b ≥ lgn

Choosing r = lgn yields a running time of Ө(bn/lgn)

If lgn > r > lgn, Time = Ω(bn/lgn)