孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

在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)          // constructor
11       {
12       a = new long[max];                 // create the array
13       nElems = 0;                        // no items yet
14       }
15 //--------------------------------------------------------------
16    public void insert(long value)    // put element into array
17       {
18       a[nElems] = value;             // insert it
19       nElems++;                      // increment size
20       }
21 //--------------------------------------------------------------
22    public void display()             // displays array contents
23       {
24       for(int j=0; j<nElems; j++)       // for each element,
25          System.out.print(a[j] + " ");  // display it
26       System.out.println("");
27       }
28 //--------------------------------------------------------------
29    public void insertionSort()
30       {
31       int in, out;
32 
33       for(out=1; out<nElems; out++)     // out is dividing line
34          {
35          long temp = a[out];            // remove marked item
36          in = out;                      // start shifts at out
37          while(in>0 && a[in-1] >= temp) // until one is smaller,
38             {
39             a[in] = a[in-1];            // shift item to right
40             --in;                       // go left one position
41             }
42          a[in] = temp;                  // insert marked item
43          }  // end for
44       }  // end insertionSort()
45 //--------------------------------------------------------------
46    }  // end class ArrayIns
47 ////////////////////////////////////////////////////////////////
48 class InsertSortApp
49    {
50    public static void main(String[] args)
51       {
52       int maxSize = 100;            // array size
53       ArrayIns arr;                 // reference to array
54       arr = new ArrayIns(maxSize);  // create the array
55 
56       arr.insert(77);               // insert 10 items
57       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 items
68 
69       arr.insertionSort();          // insertion-sort them
70 
71       arr.display();                // display them again
72       }  // end main()
73    }  // end class InsertSortApp

 

posted on 2012-05-05 20:38  孤独的猫  阅读(319)  评论(0编辑  收藏  举报