This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Sorting - Selection SortSorting - Selection Sort
Cmput 115 - Lecture 10Department of Computing Science
Often when we are sorting elements in an Array, the physical size of the array is larger than its logical size (the number of “real” elements it contains).
To accommodate this, we add the logical size of the array as an extra parameter to our sorting methods.
If we know the logical size and physical size are the same, we can omit this extra parameter. Why wouldn’t we expect them to always be the same?
How many comparison operations are required for a How many comparison operations are required for a selection sort of an n-element collection?selection sort of an n-element collection?
The sort method executes getLargestgetLargest in a loop for the indexes: k = n-1, n-2, … 1.
Each time getLargest is executed for an index, k, it does a comparison in a loop for the indexes: k-1, k-2, … 0. This is k comparisonsk comparisons.
How many assignment operations are required for a How many assignment operations are required for a selection sort of an n-element collection?selection sort of an n-element collection?
The only time we do an assignment is in a reference exchange which takes three assignments.
The sort method executes swap() in a loop for the indexes: k = n-1, n-2, … 1.
When we are sorting elements in a Vector, the Vector knows both its logical and physical size so we don’t need any extra parameters in the sort method.
However, we must access the elements in a Vector using the message elementAt() and we must cast the elements as we access them.
We must modify elements in a Vector using the message setElementAt().
public static int getMaxIndex(Vector aVector, int last) {// pre: 0 <= last < aVector.size// pre: 0 <= last < aVector.size// post: return the index of the max value in the // post: return the index of the max value in the // given Vector up to the last index// given Vector up to the last index
int maxIndex; //index of largest object//index of largest objectint index; //index of inspected element//index of inspected element
maxIndex = last;for (index = last - 1; index >= 0; index--) {
if (((Comparable) aVector.elementAt(index)).compareTo( (Comparable) aVector.elementAt(maxIndex)) > 0)