// 选择排序算法的Java实现
public class SelectionSort {
// 选择排序方法
public static void selectionSort(int[] arr) {
int n = arr.length;
// 遍历数组中的每一个元素
for (int i = 0; i < n - 1; i++) {
// 假设当前元素是最小值的索引
int minIndex = i;
// 在未排序部分查找最小值
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 将找到的最小值与当前元素交换位置
if (minIndex != i) {
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
// 测试代码
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
System.out.println("排序前:");
for (int num : arr) {
System.out.print(num + " ");
}
System.out.println();
selectionSort(arr);
System.out.println("排序后:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
选择排序的基本思想:选择排序是一种简单直观的排序算法。它的工作原理是每一次从未排序的部分中找到最小(或最大)的元素,将其放到已排序部分的末尾。
外层循环:遍历数组中的每一个元素,假设当前元素是最小值的索引。
内层循环:在未排序部分查找最小值的索引。如果找到比当前假设最小值更小的元素,则更新最小值的索引。
交换元素:将找到的最小值与当前元素交换位置,确保每次迭代后,最小值都被放置在正确的位置上。
测试代码:在 main 方法中定义了一个数组,并调用 selectionSort 方法对其进行排序,最后输出排序前后的结果。
下一篇:java 字符串匹配
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站