JAVA排序演算法實現代碼-插入排序
- /**
- * JAVA排序演算法實現代碼-插入排序。
- *
- * @author 老紫竹 JAVA世紀網(java2000.net)
- *
- */
- public class Test {
- public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 預設資料數組
-
- public static void main(String args[]) {
- int i; // 迴圈計數變數
- int Index = a.length;// 資料索引變數
-
- System.out.print("排序前: ");
- for (i = 0; i < Index - 1; i++)
- System.out.print(" " + a[i] + " ");
- System.out.println("");
-
- InsertSort(Index - 1); // 選擇排序
- // 排序後結果
- System.out.print("排序後: ");
- for (i = 0; i < Index - 1; i++)
- System.out.print(" " + a[i] + " ");
- System.out.println("");
- }
-
- public static void InsertSort(int Index) {
- int i, j, k; // 迴圈計數變數
- int InsertNode; // 欲插入資料變數
-
- for (i = 1; i < Index; i++) // 依序插入數值
- {
- InsertNode = a[i]; // 設定欲插入的數值
- j = i - 1; // 欲插入數組的開始位置
- // 找適當的插入位置
- while (j >= 0 && InsertNode < a[j]) {
- a[j + 1] = a[j];
- j--;
- }
- a[j + 1] = InsertNode; // 將數值插入
- // 列印目前排序結果
- System.out.print("排序中: ");
- for (k = 0; k < Index; k++)
- System.out.print(" " + a[k] + " ");
- System.out.println("");
- }
- }
- }
/** * JAVA排序演算法實現代碼-插入排序。 * * @author 老紫竹 JAVA世紀網(java2000.net) * */public class Test { public static int[] a = { 10, 32, 1, 9, 5, 7, 12, 0, 4, 3 }; // 預設資料數組 public static void main(String args[]) { int i; // 迴圈計數變數 int Index = a.length;// 資料索引變數 System.out.print("排序前: "); for (i = 0; i < Index - 1; i++) System.out.print(" " + a[i] + " "); System.out.println(""); InsertSort(Index - 1); // 選擇排序 // 排序後結果 System.out.print("排序後: "); for (i = 0; i < Index - 1; i++) System.out.print(" " + a[i] + " "); System.out.println(""); } public static void InsertSort(int Index) { int i, j, k; // 迴圈計數變數 int InsertNode; // 欲插入資料變數 for (i = 1; i < Index; i++) // 依序插入數值 { InsertNode = a[i]; // 設定欲插入的數值 j = i - 1; // 欲插入數組的開始位置 // 找適當的插入位置 while (j >= 0 && InsertNode < a[j]) { a[j + 1] = a[j]; j--; } a[j + 1] = InsertNode; // 將數值插入 // 列印目前排序結果 System.out.print("排序中: "); for (k = 0; k < Index; k++) System.out.print(" " + a[k] + " "); System.out.println(""); } }}
運行結果
排序前: 10 32 1 9 5 7 12 0 4
排序中: 10 32 1 9 5 7 12 0 4
排序中: 1 10 32 9 5 7 12 0 4
排序中: 1 9 10 32 5 7 12 0 4
排序中: 1 5 9 10 32 7 12 0 4
排序中: 1 5 7 9 10 32 12 0 4
排序中: 1 5 7 9 10 12 32 0 4
排序中: 0 1 5 7 9 10 12 32 4
排序中: 0 1 4 5 7 9 10 12 32
排序後: 0 1 4 5 7 9 10 12 32