what is bubble sort?

Before explaining what is bubble sort. First we need to understand what is sorting means?

Sorting means arranging the data or elements in a particular way. For example You given a array of numbers {1,5,10,8,3,1} which are un-order. You asked to arrange the elements in right order which are {1,1,3,5,8,10}.

So, Now you know the concept of sorting. let’s see the basic sorting algorithm called bubble sort.

How Bubble sort will work?

Bubble sort is a comparison based algorithm which compare each pair of adjacent items and swapping them if they are in the wrong order.

Code in java

public static void main(String[] args) {
        int[] bubble = {4,2,8,10,5};
        int flag =0;
        for (int i=0;i<bubble.length-1;i++){ 
            for (int j=0;j<bubble.length-1-i;j++){
                if (bubble[j]>bubble[j+1]){
                    int temp = bubble[j];
                    bubble[j] = bubble[j+1];
                    bubble[j+1] = temp;
                    flag = 1;
                }
            }
            if (flag== 0){
                break;
            }
        }

        for (int k=0;k<bubble.length;k++){
            System.out.println(bubble[k]);
        }
    }

Leave a comment