Modify the selection sort algorithm so it avoids the element move step if the element is already in the correct position. On what basis would you decide that the cost of this extra check outweighs the cost of not doing the check?

What will be an ideal response?


```
Solution is below and also with the Instructor’s code.
You make the change based on the likelihood that the swap won’t actually move a data element. If the likelihood of this is small, doing the extra check for all the cases where data will be moved becomes expensive.

/**
* Sort an array of integers in ascending order using selection sort.
* @param a the array of integers to sort
* @throws NullPointerException if the array object is null
*/
public static void selectionSort( int[] a ) {
if ( a == null ) {
throw new NullPointerException();
}

// while the size of the unsorted section is > 1
for ( int unsortedSize = a.length; unsortedSize > 1; unsortedSize-- ) {
// find the position of the largest element in the unsorted part
int maxPos = 0;
for ( int pos = 1; pos < unsortedSize; pos++ ) {
if ( a[pos] > a[maxPos] ) {
maxPos = pos;
}
}
// postcondition: maxPos is the position of the largest element in
// the unsorted part

if ( maxPos != unsortedSize - 1 )
{
// Swap the largest value with the last value in the unsorted part
int temp = a[unsortedSize - 1];
a[unsortedSize - 1] = a[maxPos];
a[maxPos] = temp;
}
}
}

```

Computer Science & Information Technology

You might also like to view...

Which of the following is not a floating point data type in C?

a. float b. double c. long d. long double e. none of the above

Computer Science & Information Technology

Consider the following relation for published books:

BOOK (Book_title, Authorname, Book_type, Listprice, Author_affil, Publisher) Author_affil referes to the affiliation of the author. Suppose the following dependencies exist: Book_title -> Publisher, Book_type Book_type -> Listprice Author_name -> Author-affil (a) What normal form is the relation in? Explain your answer. (b) Apply normalization until you cannot decompose the relations further. State the reasons behind each decomposition.

Computer Science & Information Technology

?A form with a main form and a subform includes two sets of navigation buttons. The navigation buttons at the bottom of the subform select records from the _____.

A. ?related table in the main form B. ?related table in the subform C. ?primary table in the main form D. ?primary table in the subform

Computer Science & Information Technology

Compute the area of a rectangle with 5-inch height and a 6-inch width.

What will be an ideal response?

Computer Science & Information Technology