數組排序

題目詳情

本題來自caopengcs,只要你有興趣,每個人都可以出題(出題入口在主頁右側邊欄“貢獻題目”->“我要發佈”內),以下是題目詳情:

給定一個包含1-n的數列,我們通過交換任意兩個元素給數列重新排序。求最少需要多少次交換,能把數組排成按1-n遞增的順序,其中,數組長度不超過100。

例如:

原數組是3,2,1, 我們只需要交換1和3就行了,交換次數爲1,所以輸出1。

原數組是2,3,1,我們需要交換2和1,變成1,3,2,再交換3和2,變爲1,2,3,總共需要的交換次數爲2,所以輸出2。


函數頭部:

C/C++

int run(const int *a,int n);

java

class solution {

public static int run(int [] a)

}


public class solution {
   public static int  run(int []a) {
        if(a == null || a.length == 0) return 0;
        int start = 0;
        // count swap
        int swapTimes = 0;
        int max = a[0];
        int maxIndex = 0;
        while(true) {
            for(int i = start; i < a.length; i++) {
                max = a[maxIndex];
                if(max > a[i]) {
                    max = a[i];
                    maxIndex = i;
                }
            }
              
            if(maxIndex != start) {
                int tmp = a[start];
                a[start] = max;
                a[maxIndex] = tmp;
                swapTimes ++;
            }
            start ++;
            maxIndex = start;
              
            if(start == a.length) {
                break;
            }
        }
        return swapTimes;
    }
    //start 提示:自動閱卷起始唯一標識,請勿刪除或增加。
    public static void main(String args[])
    {
        int a[] = {2, 3, 1};
        System.out.println("Array  {2, 3, 1}, Swap times :" + run(a));
        int b[] = {3, 2, 1};
        System.out.println("Array {3, 2, 1}, Swap times : " + run(b));
    }
    //end //提示:自動閱卷結束唯一標識,請勿刪除或增加。
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章