創建一個有序的數組,之後從從無序數組中進行一個個插入,變成有序數組。
代碼實現:
1 public class InsertSort {
2 InsertSort(int a[]){
3 int length = a.length;
4 for(int j = 1; j <= length - 1; j++){ //進行循環
5 int i = j - 1;
6 int temp = a[j]; //要插入的數字
7 while(a[i] > temp){ //在已排好序的序列中尋找應放入的位置
8 a[i + 1] = a[i]; //把較大的數前移
9 i --; //繼續比較下一個數
10 if(i < 0)
11 break;
12 }
13 a[i + 1] = temp;
14 }
15 }
16 public static void main(String args[]){
17 int a[] = {6,8,9,43,89,5,7,3,};
18 InsertSort s = new InsertSort(a);
19 for(int n:a)
20 System.out.println(n);
21 }
22 }