手记

插入排序算法优化(Java)

/**
 * Created by yuyong on 2017/3/2.
 */
public class InsertionSort {

    public void insertionSort(int arr[], int n) {

        for (int i = 1; i < n; i++) {

            int temp = arr[i];
            int j;
            for (j = i; j > 0 && arr[j - 1] > temp; j--) {
                arr[j] = arr[j - 1];
            }
            arr[j] = temp;
        }

    }

    public static void main(String[] args) {

        int[] a = {10, 8, 1, 5, 2, 9, 7, 6, 4, 3};

        InsertionSort is = new InsertionSort();
        is.insertionSort(a, 10);
        for (int i = 0; i < 10; i++) {
            System.out.print(a[i] + " ");
        }

    }

}
3人推荐
随时随地看视频
慕课网APP