class SelectSort { public static void main (String[] args) { int[] a = {3, 9,1, 8, 2, 4, 5, 6, 7}; print(a); System.out.println("After SelectSort:"); selectSort(a); print(a); } private static void print(int[] a) { for(int i=0; i<a.length; ++i) { System.out.print(a[i] + " "); } System.out.println(); } // private static void selectsort(int[] a) { // for(int i=0; i<a.length-1; ++i) { // for(int j=i+1; j<a.length; ++j){ // if(a[j] < a[i]) { // int tmp = a[j]; // a[j] = a[i]; // a[i] = tmp; // } // } // } // } // Improved version private static void selectSort(int[] a) { int min, tmp; for(int i=0; i<a.length-1; ++i) { min = i; for(int j=i+1; j<a.length; ++j){ if(a[j] < a[min]) { min = j; } } tmp = a[min]; a[min] = a[i]; a[i] =tmp; } } }
SelectSort.java
最新推荐文章于 2025-12-02 17:50:12 发布
本文介绍了一个简单的选择排序算法实现过程,通过定义一个类`classSelectSort`并使用Java语言进行编码,展示了如何对一个整数数组进行排序。该实现首先打印原始数组,然后通过选择排序算法对数组进行排序,并再次打印已排序的数组。改进版的选择排序通过记录最小元素的位置减少了不必要的元素交换。
5914

被折叠的 条评论
为什么被折叠?



