Search code examples
javaarrayssortingdata-structuresbubble-sort

Bubble sort algorithm issue when the size of array is seven


public class BubbleSort {
   public static void main(String[] args) {
      int[] arr1 = {2, 34, 65, 65, 10, 32, 45};
      int[] arr2 = {2, 65, 65, 10, 32, 45};
      int[] arr3 = {2, 34, 65, 65, 32, 45};
      int[] arr4 = {2, 12, 15, 34, 65, 65, 32, 45};
      int[] arr5 = {2, 34, 65, 65, 20, 32, 45};
      bubbleSort(arr1, 1);
      bubbleSort(arr2, 2);
      bubbleSort(arr3, 3);
      bubbleSort(arr4, 4);
      bubbleSort(arr5, 5);
   }

   public static void bubbleSort(int[] arr, int id) {
      for (int i = 0; i < arr.length; i++) {
         for (int j = 0; j < arr.length - 1; j++) {
            if (arr[j] > arr[j + 1]) {
               int tmp = arr[j + 1];
               arr[j + 1] = arr[j];
               arr[j] = tmp;
            }
         }
         System.out.println("This is Arr " + id + " " + arr[i]);
      }
   }
}

I am having an issue with my bubble sort implementation in java where I am sorting in ascending mode but as you can see when you run bubbleSort(arr1) and bubbleSort(arr5) it is returning weird values and it's not the result I'm expecting. What seems to be the problem with this?

Results

arr1 result arr5 result


Solution

  • Your function is correct, but your print is wrong, you ordered your arr5 you should print him after all iterations, your println is inside one of the for while it still ordering.

    Here's a print that I put println outside of your function.

    Code

    It's not correct formated but its what I could make Right now

    public class BubbleSort {
       public static void main(String[] args) {
          int[] arr5 = {2, 34, 65, 65, 20, 32, 45};
          bubbleSort(arr5, 5);
          
        int n = arr5.length;
        for (int i = 0; i < n; ++i)
            System.out.print(arr5[i] + " ");
        System.out.println();
       }
    
       public static void bubbleSort(int[] arr, int id) {
          for (int i = 0; i < arr.length; i++) {
             for (int j = 0; j < arr.length - 1; j++) {
                if (arr[j] > arr[j + 1]) {
                   int tmp = arr[j + 1];
                   arr[j + 1] = arr[j];
                   arr[j] = tmp;
                }
             }
             
          }
       }
    }