How to implement the bubble sort algorithm in Java

1 Answer

0 votes
public class MyClass {
    static void bubbleSort(int[] arr) {
      int len = arr.length;
      
      for (int i = 0; i < len - 1; i++) {
         for (int j = 0; j < len - i - 1; j++) {
            if (arr[j] > arr[j + 1]) {
               int temp = arr[j];
               arr[j] = arr[j + 1];
               arr[j + 1] = temp;
            }
         }
      }
    }
    public static void main(String args[]) {
        int[] arr = {6, 8, 0, 3, 1, 6, 4};
        
        bubbleSort(arr);
 
        for (int n : arr) {
            System.out.printf("%2d", n);
        }
    }
}



/*
run:

 0 1 3 4 6 6 8

*/

 



answered Mar 25, 2021 by avibootz

Related questions

1 answer 131 views
1 answer 89 views
1 answer 98 views
1 answer 110 views
1 answer 110 views
1 answer 154 views
1 answer 233 views
...