景兄弟手撕算法之插入排序

插入排序的基本思想是將一個記錄插入到已經排好序的有序表中,從而一個新的、記錄數增1的有序表

升序的插入排序:

package test1;

import java.util.Arrays;

public class InsertSort {
    public static void main(String[] args) {
        int[] arr = new int[]{2,1,5,3,4};

        for(int i=0;i<arr.length;i++){
            int current = arr[i];//取出當前要和已排序序列比較的元素

            int preIndex = i-1;//在有序區間往前掃描指針

            while (preIndex >=0 && arr[preIndex]>current){
                arr[preIndex+1]=arr[preIndex];
                preIndex--;
            }
            arr[preIndex+1] = current;
            System.out.println(Arrays.toString(arr));
        }
    }
}

輸出結果:

[2, 1, 5, 3, 4]
[1, 2, 5, 3, 4]
[1, 2, 5, 3, 4]
[1, 2, 3, 5, 4]
[1, 2, 3, 4, 5]

 

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