Advertisement
Aldin-SXR

BubbleSort.java

Mar 13th, 2020
206
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.80 KB | None | 0 0
  1. package ds.bubble.sort;
  2.  
  3. public class BubbleSort {
  4.    
  5.     /* Swap marker; whether there was a swap in the inner loop */
  6.     static boolean swapped;
  7.    
  8.     /* Perform the bubble sort algorithm */
  9.     public static void sort(int[] elements) {
  10.         for (int i = 0; i < elements.length; i++) {                
  11.             for (int j = 1; j < elements.length - i; j++) {        
  12.                 if (elements[j - 1] > elements[j]) {               
  13.                     swap(elements, j - 1, j);                      
  14.                 }
  15.             }
  16.            
  17.             /* If no two elements were swapped by inner loop, then break  */
  18.             if (swapped == false) {
  19.                 break;
  20.             }
  21.         }
  22.     }
  23.    
  24.     /* Swap two array elements: elements[a] with elements[b] */
  25.     public static void swap(int[] elements, int a, int b) {
  26.         int tmp = elements[a];
  27.         elements[a] = elements[b];
  28.         elements[b] = tmp;
  29.         swapped = true; // a swap has occurred
  30.     }
  31.    
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement