Define Bubble sort?
Bubble sorting like a bubble. Highest weight number will move to top.
Array: [50,13,8,5,12]
Outer loop doing n - 1 times
Inside loop moves the highest number to top one by one. Next time has no need to test moved bubble numbers. So inside looping is n - i - 1.
|
|
|
|
|
index of array is starts from down to top |
50 moved to top as like bubble in water |
this move will not touch already moved 50 |
this move will not touch already moved 50,13 |
this move will not touch already moved 50,13, 12 |
|
Example Bubble sort in JAVA
public class BubbleSort {
public static void display(int numbers[]){
for (int i=0;i<numbers.length;i++){
System.out.print(numbers[i]+"\t");
}
System.out.println();
}
public static void main(String args[]) throws Exception{
int numbers[] = {48,34,5,12,8};
for (int i=0;i<numbers.length-1;i++){
for (int j=0;j<numbers.length-i-1;j++){
if (numbers[j] > numbers[j+1]){
int t = numbers[j+1];
numbers[j+1] = numbers[j];
numbers[j] = t;
}
}
}
display(numbers);
}
}
|
Looping style
input array
[50,13,8,5,12]
i = 0; j:0 to n-i
[50,13,8,5,12]
[13,50,8,5,12]
[13,8,50,5,12]
[13,8,5,50,12]
[13,8,5,12,50]
i=1; j: 0 to n-i
[8,13,5,12,50]
[8,5,13,12,50]
[8,5,12,13,50]
i=2; j: 0 to n-i
[5,8,12,13,50]
i=3; j: 0 to n-i
[5,8,12,13,50]
|