Counting Sort-Sorting Algorithm Design and Analysis-Lecture Slides, Slides of Design and Analysis of Algorithms

This lecture is part of lecture series for Design and Analysis of Algorithms course. This course was taught by Dr. Bhaskar Sanyal at Maulana Azad National Institute of Technology. It includes: Design, Analysis, Algorithms, Counting, Sort, Linear, Time, Auxiliary, Storage, Loop, Running

Typology: Slides

2011/2012

Uploaded on 07/11/2012

dharmadaas
dharmadaas 🇮🇳

4.3

(55)

262 documents

1 / 20

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
COUNTING SORT
Design & Analysis of Algorithms
Docsity.com
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14

Partial preview of the text

Download Counting Sort-Sorting Algorithm Design and Analysis-Lecture Slides and more Slides Design and Analysis of Algorithms in PDF only on Docsity!

COUNTING SORT

Design & Analysis of Algorithms

Sorting in linear time

Counting sort: No comparisons between elements.

• Input : A [1.. n ], where A [ j ]{1, 2, …, k }.

• Output : B [1.. n ], sorted.

• Auxiliary storage : C [1.. k ].

Counting-sort example

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 2 3 4

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 0 0 0 0 1 2 3 4 for i  1 to k do C [ i ]  0

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 0 0 1 1 2 3 4 for j  1 to n do C [ A [ j ]]  C [ A [ j ]] + 1 ⊳ C [ i ] = |{key = i }|

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 0 1 1 1 2 3 4 for j  1 to n do C [ A [ j ]]  C [ A [ j ]] + 1 ⊳ C [ i ] = |{key = i }|

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 0 2 2 1 2 3 4 for j  1 to n do C [ A [ j ]]  C [ A [ j ]] + 1 ⊳ C [ i ] = |{key = i }|

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 0 2 2 1 2 3 4 C' : 1 1 2 2 for i  2 to k do C [ i ]  C [ i ] + C [ i – 1] ⊳ C [ i ] = |{key  i }|

A : 4 1 3 4 3

B :

1 2 3 4 5 C : 1 0 2 2 1 2 3 4 C' : 1 1 3 5 for i  2 to k do C [ i ]  C [ i ] + C [ i – 1] ⊳ C [ i ] = |{key  i }|

A : 4 1 3 4 3

B : 3

1 2 3 4 5 C : 1 1 3 5 1 2 3 4 C' : 1 1 2 5 for jn downto 1 do B [ C [ A [ j ]]]  A[ j ] C [ A [ j ]]  C [ A [ j ]] – 1

A : 4 1 3 4 3

B : 3 3 4

1 2 3 4 5 C : 1 1 2 4 1 2 3 4 C' : 1 1 1 4 for jn downto 1 do B [ C [ A [ j ]]]  A[ j ] C [ A [ j ]]  C [ A [ j ]] – 1

A : 4 1 3 4 3

B : 1 3 3 4

1 2 3 4 5 C : 1 1 1 4 1 2 3 4 C' : 0 1 1 4 for jn downto 1 do B [ C [ A [ j ]]]  A[ j ] C [ A [ j ]]  C [ A [ j ]] – 1

Analysis

for i  1 to k do C [ i ]  0 ( n ) ( k ) ( n ) ( k ) for j  1 to n do C [ A [ j ]]  C [ A [ j ]] + 1 for i  2 to k do C [ i ]  C [ i ] + C [ i – 1] for jn downto 1 do B [ C [ A [ j ]]]  A[ j ] C [ A [ j ]]  C [ A [ j ]] – 1 ( n + k )

Running time

If k = O ( n ), then counting sort takes ( n ) time.

• But, sorting takes ( n lg n ) time!

• Where’s the fallacy?

Answer:

• Comparison sorting takes ( n lg n ) time.

• Counting sort is not a comparison sort.

• In fact, not a single comparison between

elements occurs!