JAVA学习-练习试用Java实现“选择排序”
问题:
用选择法对10个整数从小到大排序。
示例 :输入10个无序的数字,如4 85 3 234 45 345 345 122 30 12。输出排序好的10个整数,如
3
4
12
30
45
85
122
234
345
345。
解答思路:
以下是使用 Java 实现选择排序的代码:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] array = new int[10];
System.out.println("请输入 10 个整数:");
for (int i = 0; i < 10; i++) {
array[i] = scanner.nextInt();
}
selectionSort(array);
System.out.println("排序后的数组:");
for (int num : array) {
System.out.print(num + " ");
}
}
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
if (minIndex!= i) {
int temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
}
}
上述代码中,首先定义了一个'selectionSort'方法,用于实现选择排序的逻辑。在'main'方法中,通过'Scanner'类获取用户输入的 10 个整数,并将它们存储在一个整数数组中。然后,调用'selectionSort'方法对数组进行排序。最后,遍历排序后的数组并打印输出。
(文章为作者在学习java过程中的一些个人体会总结和借鉴,如有不当、错误的地方,请各位大佬批评指正,定当努力改正,如有侵权请联系作者删帖。)