CodeIsland
CodeIsland

Reputation: 61

Bubble Sort not sorting correctly - Java

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)));
    }
}

Upvotes: 1

Views: 462

Answers (2)

Yashmin Sainju
Yashmin Sainju

Reputation: 61

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++;
    }

Upvotes: 0

Eran
Eran

Reputation: 393781

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;
        }
    }
}

Upvotes: 7

Related Questions