Advertisement
Aldin-SXR

comparable BubbleSort.java

Mar 19th, 2020
324
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.92 KB | None | 0 0
  1. package ds.bubble.sort.objects;
  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.     @SuppressWarnings({ "rawtypes", "unchecked" })
  10.     public static void sort(Comparable[] elements) {
  11.         for (int i = 0; i < elements.length; i++) {                
  12.             for (int j = 1; j < elements.length - i; j++) {        
  13.                 if (elements[j - 1].compareTo(elements[j]) > 0) {              
  14.                     swap(elements, j - 1, j);                      
  15.                 }
  16.             }
  17.            
  18.             /* If no two elements were swapped by inner loop, then break  */
  19.             if (swapped == false) {
  20.                 break;
  21.             }
  22.         }
  23.     }
  24.    
  25.     /* Swap two array elements: elements[a] with elements[b] */
  26.     @SuppressWarnings("rawtypes")
  27.     public static void swap(Comparable[] elements, int a, int b) {
  28.         Comparable tmp = elements[a];
  29.         elements[a] = elements[b];
  30.         elements[b] = tmp;
  31.         swapped = true; // a swap has occurred
  32.     }
  33.    
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement