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