TA的每日心情 | 开心 2021-3-12 23:18 |
---|
签到天数: 2 天 [LV.1]初来乍到
|
这是一个可以了解冒泡排序全过程的Applet演示程序,非常适合教学,如下图,按Run键自动演示对竖条进行冒泡排序,按Step键单步运行。
New 创建新的竖条,初始化排序程序; 反复点击将出现随机排列和逆序排列的竖条。
Size 选择排序竖条的数量,10或100,初始化排序程序。
Draw 重画所有竖条
Run 开始自动排序
Step 单步运行排序程序
这个Applet的源码用jad反编译而得,请下载。
下面是冒泡排序的程序:
- // bubbleSort.java
- // demonstrates bubble sort
- // to run this program: C>java BubbleSortApp
- ////////////////////////////////////////////////////////////////
- class ArrayBub
- {
- private long[] a; // ref to array a
- private int nElems; // number of data items
- //--------------------------------------------------------------
- public ArrayBub(int max) // constructor
- {
- a = new long[max]; // create the array
- nElems = 0; // no items yet
- }
- //--------------------------------------------------------------
- public void insert(long value) // put element into array
- {
- a[nElems] = value; // insert it
- nElems++; // increment size
- }
- //--------------------------------------------------------------
- public void display() // displays array contents
- {
- for(int j=0; j< nElems; j++) // for each element,
- System.out.print(a[j] + " "); // display it
- System.out.println("");
- }
- //--------------------------------------------------------------
- public void bubbleSort()
- {
- int out, in;
- for(out=nElems-1; out>=1; out--) // outer loop (backward)
- for(in=0; in< out; in++) // inner loop (forward)
- if( a[in] > a[in+1] ) // out of order?
- swap(in, in+1); // swap them
- } // end bubbleSort()
- //--------------------------------------------------------------
- private void swap(int one, int two)
- {
- long temp = a[one];
- a[one] = a[two];
- a[two] = temp;
- }
- //--------------------------------------------------------------
- } // end class ArrayBub
- ////////////////////////////////////////////////////////////////
- class BubbleSortApp
- {
- public static void main(String[] args)
- {
- int maxSize = 100; // array size
- ArrayBub arr; // reference to array
- arr = new ArrayBub(maxSize); // create the array
- arr.insert(77); // insert 10 items
- arr.insert(99);
- arr.insert(44);
- arr.insert(55);
- arr.insert(22);
- arr.insert(88);
- arr.insert(11);
- arr.insert(00);
- arr.insert(66);
- arr.insert(33);
- arr.display(); // display items
- arr.bubbleSort(); // bubble sort them
- arr.display(); // display them again
- } // end main()
- } // end class BubbleSortApp
- ////////////////////////////////////////////////////////////////
-
复制代码
源码下载:http://file.javaxxz.com/2014/11/1/000023281.zip |
|