How does this bubble sort work? (Java array)

Caporegime
Joined
12 Mar 2004
Posts
29,962
Location
England
My oracle book doesn't explain this very well.

Code:
class bubble{
public static void main(String[] args){
int nums[]={99, -10, 100123, 18, -987, 5623, 463, -9, 287, 49};

int a, b, t;
int size=10;

System.out.println("Original array is:");
for(int i=0;i<size;i++)
System.out.println(" "+nums[i]);
System.out.println();

for(a=1;a<size;a++)
for(b=size-1;b>=a;b--){
if(nums[b-1]>nums[b]){

t=nums[b-1];
nums[b-1]=nums[b];
nums[b]=t;
}}

System.out.print("Sorted array is:");
for(int i=0;i<size;i++)
System.out.print(" "+nums[i]);
System.out.println();
}}

Can someone help explain to me how this works? :p
 
It will basically just sort your array by comparing 2 values at a time till they are all in the correct order by moving each array member to its correct position one at a time. Its a very inefficient sorting algorithm however as many passes through the array are required to get to the correct sequence.

edit - sorry that wasnt very helpful. Ok it works like this, for your sequence 99, -10, 100123, 18, -987, 5623, 463, -9, 287, 49.

49 is compared to 287. 287 and 49 are switched as 49 < 287. Then, 49 is compared to -9. These are in the correct order. Next, -9 is compared to 463 and the two are switched as -9 is < 463 etc until x is compared to 99. After this run through we know the the value in position 0 of the array is the lowest number (in this case -987 will be shifted down the array to position 0). The array is then sorted through again in the same fashion and by the end of the second pass values in position 0 and 1 are known. This is done untill the entire array is in the correct order.
 
Last edited:
if(nums[b-1]>nums){

t=nums[b-1];
nums[b-1]=nums;
nums=t;
}

This does the main changing. Basically if an element [x] is bigger than [y] then swap it.
 
Back
Top Bottom