# Buble sort issue

• October 17th, 2011, 12:18 PM
kobi1988
Buble sort issue
this program will output the series of number IF among the random series there is a number larger than the consecutive number.
BUT, what happens if the numbers will be randomly order in the right order? (for example 3 5 6 7).
the "if" will not work, therefore - swapped will be false and as a result the program will not print anything..... how can i fix it?
thanks!

public class MyArray {

public static void main(String[] args) {
int[] arr = new int[10];
for(int i=0; i<arr.length; i++)
arr[i] = (int) (1 + Math.random()*100);
for(int i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
int x = arr.length;
boolean swapped;
// Sort the array using bubble sort
do {
x--;
swapped = false;
for(int j=0; j<x; j++) {
// Switch locations between arr[j] and arr[j+1]
if(arr[j]>arr[j+1]) {
swapped = true;
int temp = arr[j+1];
arr[j+1] = arr[j];
arr[j] = temp;
}
}
} while(swapped);
for(int i=0; i<arr.length; i++)
System.out.print(arr[i]+" ");
System.out.println();
}
}
• October 18th, 2011, 12:49 PM
Re: Buble sort issue
In a bubble sort, you go through an array 1..n elements n-1 times. First pass you get the biggest or smallest value and swap it with whatever was in x[1]. On the second pass you go from 2..n and store the result in x[2], and so on. As you compare each value x[2]..x[n] with x[1] you may have to swap several times in a pass.

Try sticking in a System.out.println(); for each comparison in each pass and for the array at the end of a pass for the whole array. Do you achieve the objective of the first pass by the end of the first pass? The others?
• November 6th, 2011, 03:03 PM
Karapet
Re: Buble sort issue
Hi!
This is the corresponding algorithm
...

Hope this helps
• November 7th, 2011, 08:43 AM
copeg
Re: Buble sort issue