Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class SmartestBubbleSort
- {
- public static void main (String args []){
- System.out.println("\f");
- smartestBubbleSort();
- }
- public static void smartestBubbleSort() {
- int [] nums = {22,11,9,6,3,2,1};
- int n = nums.length;
- boolean sorted = false;
- while (!sorted) {
- n--; //It is the n which will result in one less comparison happening each outer pass;
- //whereas, with the first bubble sort we could use the 'pass' variable used for the for loop.
- sorted = true;
- for (int i=0; i < n; i++) {
- if (nums[i] > nums[i+1]) {
- int temp = nums[i];
- nums[i] = nums[i+1];
- nums[i+1] = temp;
- sorted = false; //as in the second bubble sort, if swapping happens we'll want to continue, and so
- //with sorted re-set to false again, the while loop continues
- }
- }
- System.out.println(Arrays.toString(nums));
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement