单项移动为书本原有代码,双向为自己做的,不知道对不对,不过看看运行效果来看应该是对的... //-------------------------------------------------------------- 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() // -------------------------------------------------------------- public void bubbleSort2() { int outleft,outright, in; for(outleft=0,outright=nElems-1; outright>outleft; outright--,outleft++) // outer loop (backward) {for(in=outleft; in<outright; in++) // inner loop (forward) if( a[in] > a[in+1] ) // out of order? swap(in, in+1); // swap them for(in=outright; in>outleft; in--) if(a[in]< a[in-1]) swap(in,in-1); display(); } } // end bubbleSort() //-------------------------------------------------------------- private void swap(int one, int two) { long temp = a[one]; a[one] = a[two]; a[two] = temp; } //--------------------------------------------------------------原始冒泡 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() // --------------------------------------------------------------双向冒泡 public void bubbleSort2() { int outleft,outright, in;//设置左右两个标记 for(outleft=0,outright=nElems-1; outright>outleft; outright--,outleft++) // outer loop (backward) {for(in=outleft; in<outright; in++) // inner loop (forward) if( a[in] > a[in+1] ) // out of order? swap(in, in+1); // swap them for(in=outright; in>outleft; in--) if(a[in]< a[in-1]) swap(in,in-1); //display(); } } // end bubbleSort() //-------------------------------------------------------------- private void swap(int one, int two) { long temp = a[one]; a[one] = a[two]; a[two] = temp; }