选择排序--JAVA语言实现

选择排序–JAVA语言实现

public class Selection {
    /*
       对数组内的元素进行排序
     */
    public static void sort(Comparable[] a){
        /*for(int i = 0; i < a.length-1; i++){
            for(int j = i+1;j <a.length;j++){
                if(greater(a[i],a[j])){
                    exch(a,i,j);
                }
            }
        }*/
       for(int i = 0; i <= a.length-2;i++){//a.length-1为倒数第一个数,a.length-2为倒数第二个数字
            //定义一个变量,记录最小元素所在的索引,默认为参与选择排序的第一个元素所在的位置
            int minIndex = i;
            for(int j = i+1; j < a.length;j++){//必须能够取到最后一个数,要不然会有漏洞
                //需要比较最小索引minIndex处的值和索引为j的值
                if(greater(a[minIndex],a[j])){
                    minIndex = j;
                }
            }
            //交换最小元素所在索引minIndex处的值和索引i处的值
            exch(a,i,minIndex);
        }
    }
    /*
       判断v大于w
     */
    private static boolean greater(Comparable v,Comparable w){
        //大于0表示v > w
        return v.compareTo(w)>0;
    }
    /*
       交换a数组中,索引i和索引j处的值
     */
    private static void exch(Comparable[] a,int i,int j){
        Comparable temp;
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
}

发布了22 篇原创文章 · 获赞 21 · 访问量 1390

猜你喜欢

转载自blog.csdn.net/qq_43751200/article/details/104581533
今日推荐