排序之插入排序

package Test01;

public class InsertSort {
	public static void main(String[] args) {
		int[] arr = { 3, 2, 9, 8, 7, 2, 2, 0, 0 }; // 要排序的数组
		InsertionSort(arr);
		for (int i : arr) {                               //打印排序后的数组
			System.out.print(i);
		}
	}

	private static void InsertionSort(int[] arr) {            //插入排序
		if (arr == null || arr.length < 2) {
			return;
		}
//		for (int i = 1, j = i; i < arr.length; i++, j = i) {
//			while (j > 0 && arr[j] < arr[j - 1]) {
//				swap(arr, j, j - 1);
//				j--;
//			}
//		}

		for (int i = 1; i < arr.length; i++)
			for (int j = i - 1; j >= 0 && arr[j] > arr[j + 1]; j--) {
				swap(arr, j, j + 1);
			}
	}

	public static void swap(int[] arr, int a, int b) { // 交换函数
		int temp = arr[a];
		arr[a] = arr[b];
		arr[b] = temp;
	}

}
原文地址:https://www.cnblogs.com/superfly123/p/10491488.html