Bubble Sorting

BubbleSort:

This is probably the most simple algorithm for sorting but it is a bit slower than the other because it involves alot of swaps. For the each outer loop iteration inner loop iterates (array.length-1) times the condition under inner loop checks if current element of the array is greater than the element to the its right side if it is it swaps the value so the lower value comes to the lower index same process repeats again and again until the array is completely sorted.

01public class BubbleSort {
02    public static void main(String[] args) {
03     int array[] = {5 , 3 , 8 , 4 , 12};
04     int temp;
05    BubbleSort:
06     for(int i = 0; i < array.length ; i++){
07         for(int j = 0; j < (array.length – 1); j++){
08             if(array[j] > array[j+1]){
09                 temp = array[j];
10                 array[j] = array[j+1];
11                 array[j+1] = temp;}
12         }
13     }
14     System.out.println(“Array after sorting is : “);
15    for(int l: array)
16        System.out.println(l);
17    }
18 }

Output : Bubblesortfinal

If you liked it subscribe for more and if u have any questions and suggesions let me know!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s