Knowledge Walls
Venkatesan
Hyderabad, Andhra Pradesh, India
Passcode:
Bubble Sort in Sorting of Data structures & Algorithm
2243 Views
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 Array
12
5
8
13
50
1st Move
50
12
5
8
13
2nd Move
50
13
12
5
8
3rd Move
50
13
12
8
5
4th Move
50
13
12
8
5
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]
Next Topics
Next lessons of current book.
Previous Topics
Previous lessons of current book.
Best Lessons of "Data structures & Algorithm"
Top lessons which are viewed more times.
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details