Non Comparsion Sorting
Non Comparsion Sorting
The performance of comparison based algorithm you will realize that bubble, selection and insertion
sort take O(n) time to sort n items . While heap sort, quick sort and merge sort take around O(nlog n)
and it can be proved that any comparison based sorting algorithm will take at least O(nlogn)
operations to sort n elements hence we need a non comparison based algorithm which allows sort
elements in linear time.
– Counting Sort
– Radix Sort
– Bucket sort
Counting Sort: In this sorting , no comparisons between input elements occur anywhere in this
sorting .Counting sort is stable.
• Assumptions:
• Idea:
3 6 4 1 3 4 1 4
1 2 3 4 5 6
0 0 0 0 0 0
1 2 3 4 5 6
0 0 1 0 0 0
1 2 3 4 5 6
0 0 1 0 0 1
1 2 3 4 5 6
0 0 1 1 0 1
1 2 3 4 5 6
1 0 2 1 0 1
1 2 3 4 5 6
1 0 2 2 0 1
1 2 3 4 5 6
2 0 2 2 0 1
1 2 3 4 5 6
2 0 2 3 0 1
1 2 3 4 5 6
2 0 2 3 0 1
Cnew[0] =C[0]
Cnew[i] = Cnew[i-1]+C[i]
C Cnew
1 2 3 4 5 6 1 2 3 4 5 6
2 0 2 3 0 1 2 2 4 7 7 8
+ + + + +
Algorithm:
Array A
3 6 4 1 3 4 1 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
2 2 4 7 7 8
Start with last index of array which 8 with element 4 place at its correct place in the output array B
which is 7th palce with help of Cnew array and decrease Cnew[A[i]] by one
Array B
4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
2 2 4 6 7 8
Index: 7
Array B
1 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
1 2 4 6 7 8
Index: 6
Array B
1 4 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
1 2 4 5 7 8
Index: 5
Array B
1 3 4 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
1 2 3 5 7 8
Index: 4
Array B
1 1 3 4 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
0 2 3 5 7 8
Index: 3
Array B
1 1 3 4 4 4
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
0 2 3 4 7 8
Index: 2
Array B
1 1 3 4 4 4 6
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
0 2 3 4 7 7
Index: 1
Array B
1 1 3 3 4 4 4 6
1 2 3 4 5 6 7 8
Cnew
1 2 3 4 5 6
0 2 2 4 7 7