Advertisement
mrScarlett

SmartestBubbleSort

Aug 29th, 2017
144
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.09 KB | None | 0 0
  1. import java.util.Arrays;
  2. public class SmartestBubbleSort
  3. {
  4.      public static void main (String args []){
  5.         System.out.println("\f");
  6.         smartestBubbleSort();  
  7.    
  8.  
  9. }
  10.     public static void smartestBubbleSort() {
  11.      int [] nums = {22,11,9,6,3,2,1};
  12.      int n = nums.length;
  13.      boolean sorted = false;
  14.      while (!sorted) {
  15.           n--; //It is the n which will result in one less comparison happening each outer pass;
  16.                //whereas, with the first bubble sort we could use the 'pass' variable used for the for loop.
  17.           sorted = true;  
  18.           for (int i=0; i < n; i++) {
  19.                if (nums[i] > nums[i+1]) {
  20.                     int temp = nums[i];  
  21.                     nums[i] = nums[i+1];  
  22.                     nums[i+1] = temp;
  23.                     sorted = false; //as in the second bubble sort, if swapping happens we'll want to continue, and so
  24.                                     //with sorted re-set to false again, the while loop continues
  25.                }
  26.           }
  27.           System.out.println(Arrays.toString(nums));
  28.      }
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement