Advertisement
Aldin_SXR

BubbleSort.java

Mar 11th, 2024
505
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.13 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 void sort(int[] elements) {
  7.         for (int i = 0; i < elements.length; i++)  {                // 1
  8.             swapped = false; // reset swap                          // 2
  9.  
  10.             for (int j = 1; j < elements.length - i; j++) {         // 3
  11.                 if (elements[j - 1] > elements[j]) {                // 4
  12.                     swap(elements, j - 1, j);                    // 5
  13.                 }
  14.             }
  15.  
  16.             /* If no two elements were swapped by inner loop, then break  */
  17.             if (!swapped) {                                         // 6
  18.                 break;                                              // 6
  19.             }
  20.         }
  21.     }
  22.  
  23.     /* Swap two array elements: elements[a] with elements[b] */
  24.     public static void swap(int[] elements, int a, int b) {
  25.         int tmp = elements[a];
  26.         elements[a] = elements[b];
  27.         elements[b] = tmp;
  28.         swapped = true; // a swap has occurred
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement