I`ve been trying to bubble sort an array in java for some time now, but every time it just does a few and then it follows the array list.
public void mysort() {
Random randomNumbers = new Random();
int randomArray[] = new int[20];
for (int j = 0; j <= 19; j++) {
randomArray[j] = randomNumbers.nextInt(200 + 1);
for (int k = 1; k < 20; k++) {
if (randomArray[k - 1] < randomArray[k]) {
int hjelp = randomArray[k - 1];
randomArray[k - 1] = randomArray[k];
randomArray[k] = hjelp;
}
}
}
for (int i = 0; i <= 19; i++) {
System.out.println(randomArray[i]);
}
}
How do I make my bubble sort work properly?
Elena Glibart
13-Nov-2014You should populate the array first, and THEN call the sort. You're "sorting" the array 20 times, while it's still incomplete.