Java选择排序
在这个示例中,我们创建一个java程序,实现使用选择排序对数组元素进行排序。 在选择排序算法中,搜索最低的元素并将其排列到适当的位置。用下一个最小的数字交换当前元素。
选择排序的Java实现代码示例如下 -
public class SelectionSortExample {
public static void selectionSort(int[] arr) {
for (int i = 0; i < arr.length - 1; i++) {
int index = i;
for (int j = i + 1; j < arr.length; j++) {
if (arr[j] < arr[index]) {
index = j;// searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]) {
int[] arr1 = { 9, 14, 3, 2, 43, 11, 58, 22 };
System.out.println("Before Selection Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
System.out.println();
selectionSort(arr1);// sorting array using selection sort
System.out.println("After Selection Sort");
for (int i : arr1) {
System.out.print(i + " ");
}
}
}
执行上面代码后,得到以下结果 -
Before Selection Sort
9 14 3 2 43 11 58 22
After Selection Sort
2 3 9 11 14 22 43 58
//更多请阅读:https://www.yiibai.com/java/selection-sort-in-java.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)