import java.util.*;
public class Zhangbubble
{
public static void main (String[] args)
{
int Bub[] = new int[6];
Random randy = new Random();
boolean Done = false;
for (int x=0; x<6; x++)
{
Bub[x] = randy.nextInt(100);
System.out.println (Bub[x]);
}
System.out.println ("This is the original array");
while (! Done)
{
Done = true;
for (int x = 0; x<Bub.length-1; x++)
{
if(Bub[x+1] > Bub[x])
{
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1];
Done = false;
}
else
{
Done = false;
}
}
for(int x = 0; x<6; x++)
{
System.out.print(Bub[x]+" ");
}
}
}
}
So my programming teacher asked us to make a bubble sort in java using a boolean. His example shows the code in a while loop with for loops. This code is suppose to continuously sort until it has the numbers in the array organized from least to greatest. However, I'm really lost and I can't seem to figure out where I'm going wrong. Any help would be greatly appreciated!
The problem is in your switching algorithm. You are assigning temp twice.
int temp = Bub[x];
Bub[x] = Bub[x+1];
temp = Bub[x+1]; //Here should assign Bub[x+1] to temp
//Example: Bub[x+1] = temp
edit-Actually, there could be some improvement in the sorting algorithm itself, too. Personally, I like to do it this way:
public class Sort {
private static int[] array = { 3, 8, -1, 7, 0, 3 };
public static void main(String[] args) {
for(int i = 0; i < array.length - 1; i++) {
for(int j = i + 1; j < array.length; j++) {
if(array[i] > array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
for(int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}