Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Algorithms
Lecture 7. Basic sorting algorithms
Sorting problem
Input
A sequence of n numbers a1, a2, . . . , an .
Output
A permutation (reordering) a1, a2, . . . , an of the
input sequence such that a1 a2 . . . an
(a)-(e) The iterations of the for loop of lines 1-8. In each iteration, the
black rectangle holds the key taken from A[j], which is compared with
the values in shaded rectangles to its left in the test of line 5. Shaded
arrows show array values moved one position to the right in line 6, and
black arrows indicate where the key is moved to line 8.
(f) The final sorted array.
Running time
The time cost of each statement and the number of times each
statement is executed.
More specifically:
find the smallest value in the list
switch it with the value in the first position
find the next smallest value in the list
switch it with the value in the second position
repeat until all values are in their proper places
Example
Selection Sort in Pseudocode
SelectionSort(A)
// GOAL: place the elements of A in ascending order
1 n := length[A]
2 for i := 1 to n
3 // GOAL: place the correct number in A[i]
4 j := FindIndexOfSmallest( A, i, n )
5 swap A[i] with A[j]
// L.I. A[1..i] the i smallest numbers sorted
6 end-for
7 end-procedure
FindIndexOfSmallest( A, i, n )
// GOAL: return j in the range [i,n] such
// that A[j]<=A[k] for all k in range [i,n]
1 smallestAt := i ;
2 for j := (i+1) to n
3 if ( A[j] < A[smallestAt] ) smallestAt := j
// L.I. A[smallestAt] smallest among A[i..j]
4 end-for
5 return smallestAt
6 end-procedure
Running time
n 1
n 1 n
k 1
n k n n 1
2
Worst-case Run-time Analysis