欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Java选择排序,

来源: javaer 分享于  点击 3817 次 点评:192

Java选择排序,


选择排序:

1.找到数组中最小的那个元素

2.将它和数组中第一个元素交换位置

3.在剩下的元素中找到最小的元素

4.将它与数组的第二个元素交换位置

5.如此往复,直到将整个数组排序

package sortTest;

/**
 * Created by Main on 2018/5/8.
 */
public class SelectionSort {


    public static boolean less(Comparable a,Comparable b){
        return a.compareTo(b)<0;
    }

    public static void exchange(Comparable[] a,int i,int j){
        Comparable t = a[i];
        a[i] = a[j];
        a[j] = t;
    }

    public static void selectionSort(Comparable[] a){
        for (int i = 0; i < a.length; i++) {
            int min = i;
            for (int j = i+1; j < a.length ; j++) {
                if(less(a[j],a[min])){
                    min = j;
                }
            }
            exchange(a,i,min);
        }
    }

    public static void main(String[] args) {
        Integer[] numbers = new Integer[]{1,8,9,2,6,5,7};
        selectionSort(numbers);
        for (Integer number: numbers) {
            System.out.print(number);
        }
    }
}

相关文章

    暂无相关文章
相关栏目:

用户点评