Programming With Arrays  Sorting
1
Programming With Arrays  Sorting
One of the most commonly encountered programming tasks is
sorting a list of items
.
An example is a list of
exam scores
that must be sorted from lowest to highest or
from highest to lowest.
We will describe two elementary sorting methods, namely the
selection sort
and
the
bubble sort
.
For a small list of 100 or fewer items, each of these sorts is quite satisfactory.
However, the time required to sort a really large list of items becomes an impor
tant consideration, and it makes sense to use an advanced sorting technique such as
quicksort
on larger lists.
The sorting methods, we discuss, take an unsorted array as
input and will rearrange the element values such that the elements in the resulting
array are ordered from smallest to largest.
Selection Sort
Selection sort is the simplest sorting method. The basic idea is to ﬁrst ﬁnd the
smallest item and swap it with the item at index
0
. Now the smallest item is in the
ﬁrst position. Then, we restrict our attention to the remaining items; we ﬁnd the
next smallest item and swap it with the item at index
1
. We continue this process
until we reach the index of the last element of the array.
The
Selection
Sort
method is illustrated below.
This preview has intentionally blurred sections. Sign up to view the full version.
View Full DocumentProgramming With Arrays  Sorting
2
We can express this procedure more precisely by the following algorithm.
Procedure Selection_Sort:

Input: An array A with n elements to be sorted.
Output: Array A whose element values are sorted from smallest to largest.
Step 1. Set i = 0.
Step 2. Let j be the index of the smallest element
among the elements A[i] through A[n1].
Step 3. Swap the elements A[i] and A[j].
Step 4. Set i = i + 1
// Comment: The steps 2, 3, and 4 constitute one Pass.
//
We have completed Pass i.
This is the end of the preview. Sign up
to
access the rest of the document.
 Fall '08
 Satya
 Sort

Click to edit the document details