1

I've been trying to get a simple Bubble Sort method in Java to work and I cannot see the problem why it is not working. I want the lowest element in the array to be the first and the highest the last. Here I gave the method the already sorted array with values [1, 2, 3, 4].

The output is an array [1, 3, 2, 4] - so it sorted something although it should not. Does anybody see the problem?

import java.util.Arrays;

public class BubbleSort {
    public static int [] bubblesortMethode(int sortMe[])
    {
        int nrOfSwaps = 0;

        for (int i = 0; i < sortMe.length - 1; i++)  {
            for (int j = 1; j < sortMe.length; j++) {
                if(sortMe[i] > sortMe[j]){
                    int temp  = sortMe[j];
                    sortMe[j] = sortMe[i];
                    sortMe[i] = temp;
                }
            }
            nrOfSwaps++;
        }
        System.out.println("Number of swaps" + " " + nrOfSwaps);
        return sortMe;
    }

    public static void main (String[] args) {
        int sortMe [] = {1,2,3,4};
        System.out.println(Arrays.toString(bubblesortMethode(sortMe)));
    }
}
azro
  • 53,056
  • 7
  • 34
  • 70
CodeIsland
  • 61
  • 2
  • 10
  • 2
    Try using a debugger, it'll show in details what happens – azro Mar 10 '18 at 21:28
  • 1
    Read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems for tips about how to debug your code. – Code-Apprentice Mar 10 '18 at 21:29
  • Using this to sort the array 1 to 10 yields [1, 9, 8, 7, 6, 5, 4, 3, 2, 10] – frozen Mar 10 '18 at 21:30

2 Answers2

7

if (sortMe[i] > sortMe[j]), you should swap them only if i < j. Your code swaps them even when i > j.

The inner loop variable j should start at i+1 in order to make sure j is always > i :

for (int i = 0; i < sortMe.length - 1; i++)  {
    for (int j = i + 1; j < sortMe.length; j++) {
        if(sortMe[i] > sortMe[j]){
            int temp  = sortMe[j];
            sortMe[j] = sortMe[i];
            sortMe[i] = temp;
        }
    }
}
Eran
  • 387,369
  • 54
  • 702
  • 768
  • @CodeIsland if this solves the question for you, you can mark as The Answer by clicking the check mark left of the post. (It also removed the question from the Unanswered queue) – BruceWayne Mar 10 '18 at 22:03
0

It is not necessary to initialize j as 1. Initialized j as i+1 instead. Try:

for (int i = 0; i < sortMe.length - 1; i++)  {
        for (int j = i+1; j < sortMe.length; j++) {   //instead of j = 1;
            if(sortMe[i] > sortMe[j]){
                int temp  = sortMe[j];
                sortMe[j] = sortMe[i];
                sortMe[i] = temp;
            }
        }
        nrOfSwaps++;
    }