Program work 14. Insertion Sort in Java

来源:互联网 发布:cisco 查看端口速率 编辑:程序博客网 时间:2024/06/01 08:08

最差时间复杂度: O(n*n)

最好时间复杂度: O(n), 已经排好序

平均时间复杂度: O(n*n)


Pseudocode:

for i ← 1 to length(A) - 1    j ← i    while j > 0 and A[j-1] > A[j]        swap A[j] and A[j-1]        j ← j - 1    end whileend for


Java:

package ncku.cdc.sorting;import java.util.Random;public class InsertionSort {  private int[] sequence;    public InsertionSort(int size, int range) {    sequence = new int [size];    Random rand = new Random();    for (int i = 0; i < size; i++) {      sequence[i] = rand.nextInt(range);    }  }  public static void main(String[] args) {    int size = Integer.valueOf(args[0]);    int range = Integer.valueOf(args[1]);    InsertionSort insert = new InsertionSort(size, range);        System.out.println("before insertionSort:");    SortingTools.validation(insert.getSequence(), 0);        insert.insertionSort(insert.getSequence());        System.out.println("after insertionSort:");    SortingTools.validation(insert.getSequence(), 0);  }    public void insertionSort(int[] arr) {    for (int i = 1; i < arr.length; i++) {      int key;      int j = i;      key = arr[j];      while (j > 0 && arr[j - 1] > key) {        arr[j] = arr[j - 1];        j--;      }      arr[j] = key;    }  }    public int[] getSequence() {    return sequence;  }}

程序输入: 35 200. 表示随机生成长度为35, 数字范围在[0, 200)的数组.

程序输出:

before insertionSort:
35 196 183 82 132 184 48 9 153 43 95 72 174 82 57 78 125 173 14 75 9 168 72 97 158 53 146 106 56 167 183 112 126 18 81 
after insertionSort:
9 9 14 18 35 43 48 53 56 57 72 72 75 78 81 82 82 95 97 106 112 125 126 132 146 153 158 167 168 173 174 183 183 184 196

0 0