1. 程式人生 > >Java直接插入排序

Java直接插入排序

public class InsertSort {

    public static void main(String[] args) {
        int[] nums = {3, 60, 35, 2, 45, 320, 5};
        insertSort(nums);
        for (int i = 0; i < nums.length; i++) {
            System.out.print(nums[i] + " ");
        }
    }

    public static void insertSort(int[] arr) {
        for
(int i = 1; i < arr.length; i++) { //陣列0-i的元素都是有序的,如果i-1元素比i元素的值還大,則不需要排序,反之排序 if (arr[i - 1] > arr[i]) { int temp = arr[i]; int j; for (j = i - 1; j >= 0 && arr[j] > temp; j--) { //把比temp大的元素往後騰出一個位置
arr[j + 1] = arr[j]; } arr[j + 1] = temp; } } } }