java中的排序除了冒泡以來, 再給出一種方法

排序:   有一種排序的方法,非常好理解,詳見本題的步驟,先找出最大值和最小值,把最小值打印出來后,把它存在另一個數(shù)組b當中,再刪除此最小值,之后再來一次找出最小值,打印出最小值以后,再把它存在另一個數(shù)組b當中,再刪除此最小值,這樣循環(huán)往復(fù),直到做完,你就會發(fā)覺,你已經(jīng)把排了序數(shù)放在b數(shù)組當中了,而這里的徹底刪除最小值的方法就是用比最大值還大一的數(shù)來取代最小值。(自己想想為什么?)參考后面的答案你會發(fā)覺,按照下面的四步,你已經(jīng)把一個數(shù)組排序了。 i)make a method called getMin to find the minimal value of the array. ii)make a method called getMax to find the maximum value of the array. iii) replace the minimal value with the maximum+1. iiii) sort an array.
馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。



public class Test {
    static int minPosition=0;//用這個全局變量來記錄最小數(shù)的位置索引,
    public static void main(String[] args) {
        int[] a = {6, 12, 7, 23, 4};
        int max = getMax(a);
        int[] b = new int[a.length];
        for (int j = 0; j < a.length; j++) {
            int min = getMin(a);



 /*把a數(shù)組當中最小的值,馬克-to-win給替換成max+1,這樣就相當于把原來的最小值從這個數(shù)組當中徹底清除掉了。整個循環(huán)做完,a數(shù)組就徹底廢了。*/
            a[minPosition] = max + 1;
            minPosition=0;//把minPosition重置一下, 因為最小的位置已經(jīng)不是這了。
            b[j] = min;//用此方法a數(shù)組當中的數(shù)就一個一個從小到大搗到b數(shù)組當中了
        }
        for (int j = 0; j < a.length; j++) System.out.println(b[j]);
    }
    static int getMax(int[] a) {
       int max=a[0];
       for (int i = 1; i < a.length ; i++) {
           if(max<a[i])
           {
               max=a[i];
           }
       }      
       return max;
    }
    static int getMin(int[] a) {
        int min=a[0];
        for (int i = 1; i < a.length ; i++) {
            if(min>a[i])
            {
                min=a[i];
                minPosition=i;//用這個全局變量來記錄最小數(shù)的位置索引,
            }
        }      
        return min;
    }

}

結(jié)果是:

4
6
7
12
23