排序算法之插入排序

  在插入排序中,当前索引左边的所有元素都是有序的,但它们的最终位置还不确定,为了给更小的元素腾出空间,它们可能会被移动。但是当索引到达数组的右端时,数组排序就完成了。

 1 public class InsertionSort {
 2     public static void main(String[] args) {
 3         int[] arr = { 5, 2, 4, 6, 1, 3 };
 4         sort(arr);
 5     }
 6 
 7     public static void sort(int[] arr) {
 8         for (int i = 1; i < arr.length; i++) {
 9             int j = i - 1;
10             // 从排好序的牌的最后一位向前遍历比较。如果当前牌比被比较的牌小,则交换。
11             while (j >= 0 && arr[j] > arr[i]) {
12                 int temp = arr[j];
13                 arr[j] = arr[i];
14                 arr[i] = temp;
15                 j--;
16                 i--;
17             }
18         }
19         System.out.println(Arrays.toString(arr));
20     }
21 }
原文地址:https://www.cnblogs.com/huashui/p/3194626.html