Advertisement
P_Donchev

GeeksForGeeks - Bubble Sort

Dec 17th, 2020 (edited)
450
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.35 KB | None | 0 0
  1. // Java program for implementation of Bubble Sort
  2. class BubbleSort
  3. {
  4.     void bubbleSort(int arr[])
  5.     {
  6.         int i, j, temp;
  7.         boolean swapped;
  8.         for (i = 0; i < n - 1; i++)  
  9.         {
  10.             swapped = false;
  11.             for (j = 0; j < n - i - 1; j++)  
  12.             {
  13.                 if (arr[j] > arr[j + 1])  
  14.                 {
  15.                     // swap arr[j] and arr[j+1]
  16.                     temp = arr[j];
  17.                     arr[j] = arr[j + 1];
  18.                     arr[j + 1] = temp;
  19.                     swapped = true;
  20.                 }
  21.             }
  22.  
  23.             // IF no two elements were  
  24.             // swapped by inner loop, then break
  25.             if (swapped == false)
  26.                 break;
  27.         }
  28.     }
  29.  
  30.     /* Prints the array */
  31.     void printArray(int arr[])
  32.     {
  33.         int n = arr.length;
  34.         for (int i=0; i<n; ++i)
  35.             System.out.print(arr[i] + " ");
  36.         System.out.println();
  37.     }
  38.  
  39.     // Driver method to test above
  40.     public static void main(String args[])
  41.     {
  42.         BubbleSort ob = new BubbleSort();
  43.         int arr[] = {64, 34, 25, 12, 22, 11, 90};
  44.         ob.bubbleSort(arr);
  45.         System.out.println("Sorted array");
  46.         ob.printArray(arr);
  47.     }
  48. }
  49. /* This code is contributed by Rajat Mishra */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement