apelsinkach apelsinkach - 3 years ago 138
Java Question

Having trouble with bubble sort Java

I'm try realize bubble sort and it's doesn't work! Help me find a problem.

Code:

public class Main {

public static int e=0;
public static int arraylength;
public static int[] array = new int[10];

public static void main(String[] args) {
Random random = new Random();
for(int i=0;i<array.length;++i){
array[i]=random.nextInt(10);
System.out.print(" "+array[i]);
}
arraylength=array.length;
for (int i =0;i<arraylength;i++) {
arraylength--;
for (int j = 0; j < arraylength - 1; j++) {
if (array[j] > array[j + 1]) {
e = array[j + 1];
array[j + 1] = array[j];
array[j] = e;
}
}
}
}
}


Console:

Input arr: 5 1 5 4 7 8 7 7 2 8

Output: 1 4 5 2 5 7 7 7 8 8

public class Main {

public static int e=0;
public static int arraylength;
public static int[] array = new int[10];

public static void main(String[] args) {
Random random = new Random();
for(int i=0;i<array.length;++i){
array[i]=random.nextInt(10);
System.out.print(" "+array[i]);
}

System.out.println();
arraylength=array.length;
for (int i =0;i<arraylength;i++) {
arraylength--;
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
e = array[j + 1];
array[j + 1] = array[j];
array[j] = e;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(" "+array[i]);
}
}
}


Input arr: 7 7 4 1 2 9 6 4 9 6

Output: 1 2 4 4 6 6 7 7 9 9

It works,but sometimes:

Input arr: 5 2 2 3 9 6 7 7 0 6

Output: 2 2 3 0 5 6 6 7 7 9

Answer Source

Change

for (int i =0; i<arraylength; i++) {

to

for (int i =0; i<array.length; i++) {

The outer loop needs to run once for every element in the array, and you cannot do that with the arraylength variable because you are decreasing its value i.e. after the first iteration, arraylength no longer equals array.length.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download