Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
            }
         }
         
      }
   }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading