Help me to understand Bubble sort in Java. Anyone???
Posted: Wed Nov 09, 2011 9:46 am
Can anyone help me to understand Bubble sort in Java. Here is the code from Java a Beginner's Guide book.
I understand some. But I mostly don't understand how this code works. (I mean how this is sorting). I used Google to find out more info about Bubble sort and have an understanding how it works.
What I mostly don't understand is the code below this comment.
I would really happy if some one can explain me this code line by line.
Thank you very much.
I understand some. But I mostly don't understand how this code works. (I mean how this is sorting). I used Google to find out more info about Bubble sort and have an understanding how it works.
What I mostly don't understand is the code below this comment.
Code: Select all
// This is the Bubble sort.
Code: Select all
/*
Project 5-1
Demonstrate the Bubble sort.
*/
class Bubble {
public static void main(String args[]) {
int nums[] = { 99, -10, 100123, 18, -978,
5623, 463, -9, 287, 49 };
int a, b, t;
int size;
size = 10; // number of elements to sort
// display original array
System.out.print("Original array is:");
for(int i=0; i < size; i++)
System.out.print(" " + nums[i]);
System.out.println();
// This is the Bubble sort.
for(a=1; a < size; a++)
for(b=size-1; b >= a; b–-) {
if(nums[b-1] > nums[b]) { // if out of order
// exchange elements
t = nums[b-1];
nums[b-1] = nums[b];
nums[b] = t;
}
}
// display sorted array
System.out.print("Sorted array is:");
for(int i=0; i < size; i++)
System.out.print(" " + nums[i]);
System.out.println();
}
}