⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 bubblesortb.java

📁 JAVA的一个实例] 用于展示吊桶算法的改进
💻 JAVA
字号:
// Lab1 Part B: BubbleSortB.java
// Applet sorts an array's values using an efficient bubble sort, so the number of
// comparisons will decrease by one after each pass. The bubble sort will also end
// if there is nothing to sort in a pass.
import java.awt.*;
import javax.swing.*;

public class BubbleSortB extends JApplet {

   // initialize applet
   public void init()
   {
      JTextArea outputArea = new JTextArea();
      Container container = getContentPane();
      container.add( outputArea );

      int array[] = { 2, 6, 4, 8, 10, 12, 89, 68, 45, 37 };

      String output = "Data items in original order\n";

      // append original array values to String output
      for ( int counter = 0; counter < array.length; counter++ )
         output += "   " + array[ counter ];

      bubbleSort( array );  // sort array

      output += "\n\nData items in ascending order\n";

      // append sorted\ array values to String output
      for ( int counter = 0; counter < array.length; counter++ )
         output += "   " + array[ counter ];

      outputArea.setText( output );

   } // end method init

   // sort elements of array with bubble sort
   public void bubbleSort( int array2[] )
   {
      // boolean indicating if a swap took place during pass      
      /* Declare a boolean variable here  */ 
      boolean terminate;
      // loop to control number of passes
      for ( int pass = 1; pass < array2.length; pass++ ) {
         /* Set the boolean variable to false */ 
         terminate=true;
         /* Write a for loop here to control the number of comparisons */ 
         
            // compare side-by-side elements and swap them if
            // first element is greater than second element
          for (int element=0;element<array2.length-1;element++)
          {
            
            /* Modify the body of this if statement to indicate 
               that a swap occurred */
            if ( array2[ element ] > array2[ element + 1 ] )
              { swap( array2, element, element + 1 );
			     terminate=true;  
			  }
         } // end loop to control comparisons

         // if no swaps, terminate bubble sort
         /* Write an if statement to terminate sorting of no swaps occurred */
        if (terminate)
		  {}
		else
		break;
         

       
	} // end loop to control passes

   } // end method bubbleSort

   // swap two elements of an array
   public void swap( int array3[], int first, int second )
   {
      // temporary holding area for swap
      int hold;

      hold = array3[ first ];
      array3[ first ] = array3[ second ];
      array3[ second ] = hold;
   }

} // end class BubbleSortB

⌨️ 快捷键说明

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