插入排序——Insertion Sort

 

基本思想:

在要排序的一組數中,假定前n-1個數已經排好序,如今將第n個數插到前面的有序數列中,使得這n個數也是排好順序的。如此反覆循環,直到所有排好順序。java

過程:

平均時間複雜度:O(n2)spa

java代碼實現:

/**
 * 插入排序
 * 
 * @author Administrator
 *
 */
public class InsertSort {

    /*
     * 基本思想:
     * 在要排序的一組數中,假定前n-1個數已經排好序,如今將第n個數插到前面的有序數列中,使得這n個數也是排好順序的。如此反覆循環,直到所有排好順序。
     * 
     * 平均時間複雜度:O(n2)
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] arr = new int[] { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12, 3, 8, 55, 44,
                -10 };
        insertSort(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + "  ");
        }
    }

    private static void insertSort(int[] a) {
        for (int i = 0; i < a.length - 1; i++) {
            for (int j = i + 1; j > 0; j--) {
                if (a[j] < a[j - 1]) {
                    int temp = a[j];
                    a[j] = a[j - 1];
                    a[j - 1] = temp;
                } else {
                    break;
                }
            }
        }
    }

}
相關文章
相關標籤/搜索