下麵我們創建一個java程式,實現使用插入排序對數組元素進行排序。 插入排序對於小元素是有好處的,因為排序大量元素它需要更多的時間。

讓我們來看看一個簡單的java程式,使用插入排序演算法對數組進行排序。
public class InsertionSortExample {
    public static void insertionSort(int array[]) {
        int n = array.length;
        for (int j = 1; j < n; j++) {
            int key = array[j];
            int i = j - 1;
            while ((i > -1) && (array[i] > key)) {
                array[i + 1] = array[i];
                i--;
            }
            array[i + 1] = key;
        }
    }
    public static void main(String a[]) {
        int[] arr1 = { 9, 14, 3, 2, 43, 11, 58, 22 };
        System.out.println("Before Insertion Sort");
        for (int i : arr1) {
            System.out.print(i + " ");
        }
        System.out.println();
        insertionSort(arr1);// sorting array using insertion sort
        System.out.println("After Insertion Sort");
        for (int i : arr1) {
            System.out.print(i + " ");
        }
    }
}
執行上面代碼,輸出結果如下:
Before Insertion Sort
9 14 3 2 43 11 58 22
After Insertion Sort
2 3 9 11 14 22 43 58
						上一篇:
								Java基礎實例程式
												下一篇:
								Java面向對象(OOP)概念
					
					