forked from HarryDulaney/intro-to-java-programming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Exercise07_20.java
57 lines (50 loc) · 1.74 KB
/
Exercise07_20.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package ch_07;
import java.util.Arrays;
import java.util.Scanner;
/**
* *7.20 (Revise selection sort) In Section 7.11, you used selection sort to sort an array.
* The selection-sort method repeatedly finds the smallest number in the current
* array and swaps it with the first.
* <p>
* Rewrite this program by finding the largest number and swapping it with the last.
* <p>
* Write a test program that reads in ten double
* 3.34 4.33 18.22 111.42 4.98 3.33 90.321 6.6 7.7 8.8
* numbers, invokes the method, and displays the sorted numbers.
*
* @author Harry D.
*/
public class Exercise07_20 {
public static void main(String[] args) {
double[] arr = new double[10];
Scanner in = new Scanner(System.in);
System.out.println("Enter ten decimal numbers: ");
for (int i = 0; i < 10; i++) {
arr[i] = in.nextDouble();
}
selectionSort(arr);
System.out.println("Sorted high to low: ");
System.out.println(Arrays.toString(arr));
}
/**
* Selection sort implementation using Max value
*/
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
// Find the minimum in the list[i..list.length-1]
double currentMax = list[i];
int currentMaxIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMax < list[j]) {
currentMax = list[j];
currentMaxIndex = j;
}
}
// Swap list[i] with list[currentMaxIndex] if necessary
if (currentMaxIndex != i) {
list[currentMaxIndex] = list[i];
list[i] = currentMax;
}
}
}
}