Search code examples
javaeclipsesortingbubble-sort

What is wrong with this bubble sort algorithm I created?


int arraySize = 10;
int[] array = new int[30];

public void generateRandomArray() {
    for (int i=0; i < arraySize; i++) {
        array[i] = (int) (Math.random() * (10-1)+1);
    }
}

public void bubbleSort(){
    for (int i=0; i < arraySize; i++) {
        if (array[i] < array[i+1]) {
        } else if (array[i] > array[i+1]) {
            int storeNumber = array[i];
            array[i] = array[i+1];
            array[i+1] = storeNumber;
        }
    }
}

In my driver class I have:

public class Driver {
    public static void main(String[] args) {
        DataOperations array = new DataOperations();
        array.generateRandomArray();
        array.printArray();
        array.bubbleSort();
        array.printArray();
    }
}

Before the bubble sort I get:

0-1
1-8
2-1
3-2
4-9
5-1
6-7
7-2
8-5
9-3

After the bubble sort I get:

0-1
1-1
2-2
3-8
4-1
5-7
6-2
7-5
8-3
9-0

I am not exactly sure what is wrong. Can anyone help me figure this out?


Solution

  • Bubble sort is O(n^2) you need to repeat your inner loop n times.

    for(int j=0;j<arraySize;j++) {
    for(int i=0;i<arraySize;i++){
        if(array[i]<array[i+1]){
        }else if(array[i]>array[i+1]){
            int storeNumber=array[i];
            array[i]=array[i+1];
            array[i+1]=storeNumber;
        } 
    }
    }