排序之插入排序


  插入排序數組

/**
 * 對指定的 int 型數組按數字升序進行插入排序
 * @param a 待排序的數組
 */
public static void sortInsertion(int[] a) {
    int flag = 0;//標記須要插入的位置
    int temp = 0;//存儲待插入的數
    for (int i = 1; i < a.length; i++) {
        temp = a[i];
        for (int j = i; j > 0; j--) {
            if (a[j-1] > temp) {
                a[j] = a[j-1];
                flag = j-1;
            }else {
                flag = j;
                break;
            }
        }
        a[flag] = temp;
    }
}
    
相關文章
相關標籤/搜索