Sorting (ii)

COMP2521 20T2 ♢ Sorting (ii) [0/11]
❖ Summary of Sorting Methods


Sorting = arrange a collection of N items in ascending order ...

Elementary sorting algorithms:   O(N2) comparisons

Advanced sorting algorithms:   O(NlogN) comparisons Most are intended for use in-memory (random access data structure).

Merge sort adapts well for use as disk-based sort.

COMP2521 20T2 ♢ Sorting (ii) [1/11]
❖ ... Summary of Sorting Methods

Other properties of sort algorithms: stable, adaptive

Selection sort:

Bubble sort: Insertion sort:
COMP2521 20T2 ♢ Sorting (ii) [2/11]
❖ ... Summary of Sorting Methods

Other properties of sort algorithms: stable, adaptive

Quicksort:

Merge sort: Heap sort:
COMP2521 20T2 ♢ Sorting (ii) [3/11]
❖ Lower Bound for Comparison-Based Sorting

All of the above sorting algorithms for arrays of n  elements

Such algorithms cannot work with less than O(n log n) comparisons


Informal proof (for arrays with no duplicates):

(continued ...)

COMP2521 20T2 ♢ Sorting (ii) [4/11]
❖ ... Lower Bound for Comparison-Based Sorting

Can view sorting as navigating a decision tree ...

[Diagram:Pics/sortingLowerBound.png]

(continued ...)

COMP2521 20T2 ♢ Sorting (ii) [5/11]
❖ ... Lower Bound for Comparison-Based Sorting

Can view the sorting process as

For n  elements, there are n!  leaves

So, for comparison-based sorting, lower bound is Ω(n log2 n).


Are there faster algorithms not based on whole key comparison?

COMP2521 20T2 ♢ Sorting (ii) [6/11]
❖ Radix Sort

Radix sort is a non-comparative sorting algorithm.

Requires us to consider a key as a tuple (k1, k2, ..., km), e.g.

Assume only small number of possible values for ki, e.g. If keys have different lengths, pad with suitable character, e.g.
COMP2521 20T2 ♢ Sorting (ii) [7/11]
❖ ... Radix Sort

Radix sort algorithm:

Example:

[Diagram:Pics/radix-overview.png]

COMP2521 20T2 ♢ Sorting (ii) [8/11]
❖ ... Radix Sort

Stable sorting (bucket sort):

// sort array A[n] of keys
// each key is m symbols from an "alphabet"
// array of buckets, one for each symbol
for each i in m .. 1 do
   empty all buckets
   for each key in A do
      append key to bucket[key[i]]
   end for
   clear A
   for each bucket in order do
      for each key in bucket do
         append to array
      end for
   end for
end for

COMP2521 20T2 ♢ Sorting (ii) [9/11]
❖ ... Radix Sort

Example:

After first pass (i = 3): After second pass (i = 2): After third pass (i = 1):
COMP2521 20T2 ♢ Sorting (ii) [10/11]
❖ ... Radix Sort


Complexity analysis:

So, time complexity for radix sort = O(mn)

Radix sort performs better than comparison-based sorting algorithms

COMP2521 20T2 ♢ Sorting (ii) [11/11]


Produced: 23 Jul 2020