insertionsorttiming.java

来自「Java 入门书的源码」· Java 代码 · 共 31 行

JAVA
31
字号
//Copyright (c) 1998, Arthur Gittleman
//This example is provided WITHOUT ANY WARRANTY either expressed or implied.

/* Sorts random numbers using the insertion sort algorithm.  Uses 
 * random data. Outputs the milliseconds taken to sort.  Use this
 * program to estimate the efficiency of insertion sort.
 */

import iopack.Io;

public class InsertionSortTiming {
  public static void main(String [] args)  {
    int size = Io.readInt("Enter the number of data items");
    int[] item = new int[size];      // allocate array to hold data        
    for (int i=0; i<size; i++)
       item[i] = (int)(100*Math.random());
    long starttime = System.currentTimeMillis();
    for (int i=1; i<size; i++) {
      int current = item[i]; 
      int j = 0;
      while (current > item[j]) j++;
      for (int k=i; k>j; k--)
        item[k] = item[k-1];
      item[j] = current;
    }
    long stoptime = System.currentTimeMillis();
    System.out.println("The time used in milliseconds is "+ (stoptime-starttime));
    Io.readString("Press any key to exit");   // Added for IDE use 
  }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?