JDEP183H
Handout 19: Sorting
October 28, 2008
Before examining record
, we assume that the preceding records
have already been
sorted; then we insert
into its proper place
among the previously sorted records.
Straight
insertion. Assume that
and that records
have been rearranged
so that
.
We compare the new value
with
,
, …, in turn, until
discovering that
should be inserted
between
and
; then we move records
, …,
, up one space and put the new record into position i +
1.
Implementation.
int numbers[];
int i, j, k;
//
assume that numbers[0] has already been sorted.
for (j = 1; j <
numbers.length; j++) {
// find the place to insert
i = 0;
while (i < j && numbers[j]
> numbers[i])
i++;
int temp = numbers[j]; // store the value first
// insertion point is i
// need to move all the other numbers by
one position
for (k = j; k > i; k--)
numbers[k] = numbers[k-1];
// now the finishing touch.
numbers[i] = temp;
}
Exchange or transposition which systematically interchange pairs of elements that are out of order until no more such pairs exist.
The bubble sort. Compare
and
, interchanging
and
if the keys are out of
order; then do the same to records
and
,
and
, etc. During this
sequence of operations, records with the largest value will move up to become
. Repetitions of the
process will get the appropriate records into positions
,
, etc., so that all records will ultimately sorted.
Implementation.
int numbers[];
int i, j, k;
int iteration = 1;
for (j = 0; j <
(numbers.length-1); j++) {
// compare it with the rest of the numbers
for (k = 0; k <
(numbers.length-iteration); k++) {
if (numbers[k] > numbers[k+1]) {
// switch
int temp = numbers[k+1];
numbers[k+1] = numbers[k];
numbers[k] = temp;
}
}
iteration++;
}
(1) Find
the smallest value; transfer the corresponding record to the output area, then
replace the value by the value “
” (which is assumed to be higher than any actual value).
(2) Repeat
step (1). This time the second smallest
key will be selected, since the smallest key has been replaced by
.
(3) Continue repeating step (i) until N records have been selected.
Requires all the
input items to be present before sorting may proceed, and it generates the
final outputs one by one in sequence.
This is essentially the opposite of insertion, where the inputs are
received sequentially but we do not know any of the final outputs until sorting
is completed.
Implementation.
int numbers[];
int i, j, k;
for (j = (numbers.length-1); j
>= 1; j--) {
// find the maximum between 0 and j
int maximum = numbers[0];
int maximumIndex = 0;
for (k = 0; k <= j; k++) {
if (numbers[k] >
maximum) {
maximum = numbers[k];
maximumIndex = k;
}
}
//
replace the records, the maximum one to the current
int temp = numbers[j];
numbers[j] = maximum;
numbers[maximumIndex] = temp;
}
* Based on Knuth (1973)