Advertisement
Aldin_SXR

Comparable BubbleSort.java

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