Advertisement
mrScarlett

Smarter Bubble Sort 2

Aug 29th, 2017
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.20 KB | None | 0 0
  1. import java.util.Arrays;
  2. public class smarterBubbleSort2
  3. {
  4.     // instance variables - replace the example below with your own
  5.      public static void main (String args []){
  6.         System.out.println("\f");
  7.         smarterBubbleSort2();  
  8.    
  9.  
  10. }
  11.     public static void smarterBubbleSort2() {
  12.      int [] nums = {22,11,9,6,3,2,1};
  13.      boolean sorted = false;
  14.      while (!sorted) {
  15.           sorted = true; //this is just an assumption, which every time except the last, will actually not be the case
  16.                          //so the last time through the while loop, when we don't get into the swap at least once,
  17.                          //the while will no longer run
  18.           for (int i = 0; i< nums.length-1; i++) { //(So this bubble sort inefficiently checks all neighbors each pass)
  19.                if (nums[i] > nums[i+1]) {
  20.                     //Swap
  21.                     int temp = nums[i];  
  22.                     nums[i] = nums[i+1];  
  23.                     nums[i+1] = temp;
  24.                     sorted = false;  //sorted goes back to false indicating that we still have to continue sorting
  25.                }
  26.                System.out.println(Arrays.toString(nums));
  27.           }
  28.      }
  29. }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement