lect7_2

lect7_2 - Programming With Arrays Sorting 1 Programming...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
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 first find the smallest item and swap it with the item at index 0 . Now the smallest item is in the first position. Then, we restrict our attention to the remaining items; we find 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.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Programming 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[n-1]. 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.
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

lect7_2 - Programming With Arrays Sorting 1 Programming...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online