插入排序是一種最簡單直觀的排序算法,它的工做原理是經過構建有序序列,對於未排序數據,在已排序序列中從後向前掃描,找到相應位置並插入。java
插入排序方法:算法
public static int[] insertionSort(int[] elements) { int temp = 0; if(null == elements || 1 >= elements.length) { // do nothing } else { System.out.println("elements:"+Arrays.toString(elements)); System.out.println("------------------------------------------------"); // 從數組的第二個元素開始遍歷,直至數組末尾 for(int i=1 ;i<elements.length; i++) { System.out.println("當前遍歷元素["+i+"]:"+elements[i]); // 當前元素的序號 int nowIndex = i; // 前一位元素的序號 int preIndex = i-1; while(preIndex >= 0) { if(elements[nowIndex] < elements[preIndex]) { // 假若當前元素比前一元素小,則將二者交換 temp = elements[preIndex]; elements[preIndex] = elements[nowIndex]; elements[nowIndex] = temp; // 繼續向前比較元素大小 nowIndex = preIndex; preIndex = preIndex - 1; } else { preIndex = -1; } } System.out.println("elements="+Arrays.toString(elements)); System.out.println("------------------------------------------------"); } } return elements; }
測試代碼:數組
public static void main(String[] args) { int[] array = {82 ,31 ,29 ,71, 72, 42, 64, 5, 110}; insertionSort(array); }
結果:測試
elements:[82, 31, 29, 71, 72, 42, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[1]:31 elements=[31, 82, 29, 71, 72, 42, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[2]:29 elements=[29, 31, 82, 71, 72, 42, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[3]:71 elements=[29, 31, 71, 82, 72, 42, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[4]:72 elements=[29, 31, 71, 72, 82, 42, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[5]:42 elements=[29, 31, 42, 71, 72, 82, 64, 5, 110] ------------------------------------------------ 當前遍歷元素[6]:64 elements=[29, 31, 42, 64, 71, 72, 82, 5, 110] ------------------------------------------------ 當前遍歷元素[7]:5 elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------ 當前遍歷元素[8]:110 elements=[5, 29, 31, 42, 64, 71, 72, 82, 110] ------------------------------------------------