在JAVA进行插入排序的代码:
1 // insertSort.java 2 // demonstrates insertion sort 3 // to run this program: C>java InsertSortApp 4 //-------------------------------------------------------------- 5 class ArrayIns 6 { 7 private long[] a; // ref to array a 8 private int nElems; // number of data items 9 //--------------------------------------------------------------10 public ArrayIns(int max) // constructor11 {12 a = new long[max]; // create the array13 nElems = 0; // no items yet14 }15 //--------------------------------------------------------------16 public void insert(long value) // put element into array17 {18 a[nElems] = value; // insert it19 nElems++; // increment size20 }21 //--------------------------------------------------------------22 public void display() // displays array contents23 {24 for(int j=0; j0 && a[in-1] >= temp) // until one is smaller,38 {39 a[in] = a[in-1]; // shift item to right40 --in; // go left one position41 }42 a[in] = temp; // insert marked item43 } // end for44 } // end insertionSort()45 //--------------------------------------------------------------46 } // end class ArrayIns47 48 class InsertSortApp49 {50 public static void main(String[] args)51 {52 int maxSize = 100; // array size53 ArrayIns arr; // reference to array54 arr = new ArrayIns(maxSize); // create the array55 56 arr.insert(77); // insert 10 items57 arr.insert(99);58 arr.insert(44);59 arr.insert(55);60 arr.insert(22);61 arr.insert(88);62 arr.insert(11);63 arr.insert(00);64 arr.insert(66);65 arr.insert(33);66 67 arr.display(); // display items68 69 arr.insertionSort(); // insertion-sort them70 71 arr.display(); // display them again72 } // end main()73 } // end class InsertSortApp