229k views
1 vote
Create a new Java project and class. Add the following method, based on the Gaddis in-chapter example. Please remember to type in this code rather than copy-and-pasting; Word loves to mangle source code.

public static void selectionSort(int[] array) {

int startScan, index, minIndex, minValue;

for (startScan = 0; startScan < (array.length - 1); startScan++) {

minIndex = startScan;

minValue = array[startScan];

for (index = startScan + 1; index < array.length; index++) {

if (array[index] < minValue) {

minValue = array[index];

minIndex = index;

}

}

array[minIndex] = array[startScan];

array[startScan] = minValue;

}

}

Create an array of ten random integers, and array of five thousand (5,000) random integers, and an array of five hundred thousand (500,000) random integers.

For each array:

Display the first ten elements of the array.

Call selection sort for the array.

Display the first ten elements of the sorted array.

Once this works, answer the following questions, and include a screenshot and your finished program at the end of the lab.

Questions:

After selectionSort is called, why can you no longer display the original randomly-generated array?

1 Answer

7 votes

Final answer:

After calling selectionSort on an array in Java, the original array is modified to be sorted, thus losing the original order of its randomly generated elements.

Step-by-step explanation:

The selectionSort method you are asked to implement in Java is an in-place sorting algorithm, meaning it sorts the array by modifying the array directly, rather than creating a new sorted array and leaving the original unchanged. Once a sorting algorithm like selectionSort is executed, the array elements are rearranged to be in sorted order; thus the original order of the randomly generated numbers is lost.

In your Java project, when you call selectionSort on an array, it reorders that array's elements in ascending order by repeatedly finding the minimum element (considering ascending order) from the unsorted part and putting it at the beginning. This operation changes the original positions of each element, therefore the original random array can no longer be displayed without having kept a separate copy before the sorting took place.

User Schanq
by
7.1k points