Sorting

COMP2521 20T2 ♢ Sorting [0/12]
❖ Sorting

Sorting involves arranging a collection of items in order


Why is sorting useful?
COMP2521 20T2 ♢ Sorting [1/12]
❖ ... Sorting


Sorting occurs in many data contexts, e.g.

Different contexts generally require different approaches
Our view of the sorting problem:
COMP2521 20T2 ♢ Sorting [2/12]
❖ The Sorting Problem

Arrange items in array slice a[lo..hi] into sorted order:

[Diagram:Pics/sorting.png]

For Item a[N],  frequently (lo == 0), (hi == N-1)

COMP2521 20T2 ♢ Sorting [3/12]
❖ ... The Sorting Problem


More formally ...

Precondition:

Postcondition:
COMP2521 20T2 ♢ Sorting [4/12]
❖ ... The Sorting Problem

We sort arrays of Items, which could be

Each Item contains a key, which could be The order of key values determines the order of the sort.

Duplicate key values are not precluded.


In our discussions, we often use the key value as if it is the whole Item

COMP2521 20T2 ♢ Sorting [5/12]
❖ ... The Sorting Problem

Properties of sorting algorithms: stable, adaptive

Stable sort:

Adaptive:

COMP2521 20T2 ♢ Sorting [6/12]
❖ ... The Sorting Problem

In analysing sorting algorithms:

Aim to minimise C and S

Cases to consider for initial order of items:

COMP2521 20T2 ♢ Sorting [7/12]
❖ Comparison of Sorting Algorithms

A variety of sorting algorithms exist

Ways to compare algorithms:
COMP2521 20T2 ♢ Sorting [8/12]
❖ Implementing Sorting

Concrete framework:

// we deal with generic Items
typedef SomeType Item;

// abstractions to hide details of Items
#define key(A) (A)
#define less(A,B) (key(A) < key(B))
#define swap(A,B) {Item t; t = A; A = B; B = t;}

// Sorts a slice of an array of Items, a[lo..hi]
void sort(Item a[], int lo, int hi);

// Check for sortedness (to validate functions)
int isSorted(Item a[], int lo, int hi);

COMP2521 20T2 ♢ Sorting [9/12]
❖ Implementing isSorted()


Implementation of the isSorted() check.

bool isSorted(Item a[], int lo, int hi)
{
   for (int i = lo; i < hi; i++) {
      if (!less(a[i],a[i+1])) return false;
   }
   return true;
}


Checks pairs  (a[lo],a[lo+1]), ... (a[hi-1],a[hi])

Check whole array  Item a[N]  via  isSorted(a, 0, N-1)

COMP2521 20T2 ♢ Sorting [10/12]
❖ Sorts on Linux

The sort command

The qsort() function Note: the comparison function is passed as a parameter; discussed elsewhere.
COMP2521 20T2 ♢ Sorting [11/12]
❖ Describing Sorting Algorithms

To describe sorting, we use diagrams like:

[Diagram:Pics/showing-sorting.png]

In these algorithms ...


See also animations by David R. Martin, Boston College, based on Sedgewick's idea
COMP2521 20T2 ♢ Sorting [12/12]


Produced: 18 Jul 2020