Selection Sort (Algorithm, and by hand)

advertisement
BIT 142
In-Class Exercises
Selection Sort (Algorithm, and by hand)
This exercise follows the same pattern as the last one, except that here
you'll be doing a Selection Sort. A Selection Sort is very similar to a Bubble Sort,
except that fewer swaps are done. The pseudo for a selection sort is given here:
For i = Array.Length -1 down to 0 (decrease by 1 each time)
{
int iLargestValueFound = 0;
For j = 0 to i
{
if( array[j] > array[ iLargestValueFound ] )
iLargestValueFound = j;
}
swap array[i] and array[iLargestValueFound]
}
In other words, it works almost like a BubbleSort does, except that instead
of swapping at each step, we wait till we've done an entire pass through the
array, and do one swap, once we've found the largest element that hasn't been
properly sorted yet.
Starting with the array pictured below, fill out the picture of the array, step
by step, in order to show how a Selection Sort operates. The first couple of steps
are filled in, as a demonstration
Given the method (defined with the SearchingAndSorting class)
void SelectionSort(int[] array)
This method will be called from main, in the following manner:
int [] nums = { 17, 12, 21, -3, 0};
SearchingAndSorting sas = new SearchingAndSorting();
sas.SelectionSort(nums);
You will start your 'trace' as follows:
Starting Point
Array
Index:
0
1
2
3
4
Value:
17
12
21
-3
0
BIT 142
In-Class Exercises
Swap 0
Array
Index:
0
1
2
3
4
Value:
17
12
0
-3
21
Swap 1
Array
Index:
0
1
2
3
4
Value:
-3
12
0
17
21
2
3
4
2
3
4
2
3
4
2
3
4
Swap 2
Array
Index:
0
1
Value:
Swap 3
Array
Index:
0
1
Value:
Swap 4
Array
Index:
0
1
Value:
Swap 5
Array
Index:
Value:
0
1
Download