Docsity

Linear Sorting - Data Structures - Lecture Slides, Slides of Data Structures and Algorithms

Partial preview of the text

Download Linear Sorting - Data Structures - Lecture Slides and more Slides Data Structures and Algorithms in PDF only on Docsity!

Linear Sorting

2

How Fast Can We Sort?

  • Selection Sort, Bubble Sort, Insertion Sort:
  • Heap Sort, Merge sort:
  • Quicksort:
  • What is common to all these algorithms?
    • Make comparisons between input elements ai < aj , ai ≤ aj , ai = aj , ai ≥ aj , or ai > aj

O(n 2 )

O(nlgn) O(nlgn) - average

4

Can we do better?

  • Linear sorting algorithms
    • Counting Sort
    • Radix Sort
    • Bucket sort
  • Make certain assumptions about the data
  • Linear sorts are NOT “comparison sorts”

5

Counting Sort

  • Assumptions:
    • n integers which are in the range [0 ... r]
    • r is in the order of n, that is, r=O(n)
  • Idea:
    • For each element x, find the number of elements x
    • Place x into its correct position in the output array

output array

7

Step 2

C (frequencies)^ Cnew (cumulative sums)

8

Algorithm

  • Start from the last element of A
  • Place A[i] at its correct place in the output array
  • Decrease C[A[i]] by one

1 2 3 4 5 6 7 8 A

1 2 3 4 5 Cnew^8

0

10

Example (cont.)

1 2 3 4 5 6 7 8 A

1 2 3 4 5 6 7 8 B

0 2 3 5 7

1 2 3 4 5 C (^8)

0

1 2 3 4 5 6 7 8 B

0 2 3 4 7

1 2 3 4 5 C (^7)

0

1 2 3 4 5 6 7 8 B

0 2 3 4 7

1 2 3 4 5 C (^8)

0

1 2 3 4 5 6 7 8 B

11

COUNTING-SORT

Alg.: COUNTING-SORT(A, B, n, k)

1. for i ← 0 **to r

  1. do** C[ i ] ← 0 3. for j ← 1 to n 4. do C[A[ j ]] ← C[A[ j ]] + 1 5. C[i] contains the number of elements equal to i 6. for i ← 1 **to r
  2. do** C[ i ] ← C[ i ] + C[i -1] 8. C[i] contains the number of elements ≤ i 9. for j ← n downto 1 10. do B[C[A[ j ]]] ← A[ j ] 11. C[A[ j ]] ← C[A[ j ]] - 1

1 n

0 k

A

C 1 n B

j

13

Analysis of Counting Sort

  • Overall time: O(n + r)
  • In practice we use COUNTING sort when r = O(n)

⇒ running time is O(n)

16

Radix Sort

  • Assumptions

d=O(1) and k =O(n)

  • Sorting looks at one column at a time
    • For a d digit number, sort the least significant digit first
    • Continue sorting on the next least significant digit, - until all digits have been sorted
    • Requires only d passes through the list

17

RADIX-SORT

Alg.: RADIX-SORT(A, d)

for i ← 1 to d do use a stable sort to sort array A on digit i (stable sort: preserves order of identical elements)

19

Analysis of Radix Sort

  • Given n numbers of d digits each, where each

digit may take up to k possible values, RADIX-

SORT correctly sorts the numbers in O(d(n+k))

  • Assuming d=O(1) and k=O(n), running time is O(n)