Simple Bubble Sort Algorithm in Java

[6033 views]




Simple Bubble Sort Algorithm in Java

Bubble Sort Algorithm is the most Simple and most Popular Sorting Algorithm. In this article you will find the Bubble Sort Algorithm implemented in Java.

Bubble Sort Example with Explanation:

Bubble Sort Example in Java with Explanation

Image Source: Medium

Worst and Average Case Time Complexity (Worst case occurs when array is completely in reverse order): O(n*n).
Best Case Time Complexity (Best case occurs when given array is already sorted ): O(n).
Auxiliary Space: O(1)
Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.

Program.java

public class Program { static void bubbleSort(int[ ] lst){ boolean swapped; int space = lst.length; //a do-while loop to prevent futher itration after the list is sorted. do{ swapped=false; //BubbleSort for(int i=0;i<space-1;i++){ if(lst[i+1]<lst[i]){ int first=lst[i]; lst[i]=lst[i+1]; lst[i+1]=first; swapped = true; } } //displays list after every sort System.out.print("==> "); for(int i=0; i<space;i++){ System.out.print(lst[i]+" "); } System.out.print("\n"); }while(swapped==true); //displays the fully bubbleSorted list. System.out.print("\n\nFinally: "); for(int each:lst){ System.out.print(each+" "); } } public static void main(String[] args) { int[] nums ={3,4,1,6,0,2,8}; bubbleSort(nums); } }

Output:

$javac Program.java $java Program ==> 3 1 4 0 2 6 8 ==> 1 3 0 2 4 6 8 ==> 1 0 2 3 4 6 8 ==> 0 1 2 3 4 6 8 ==> 0 1 2 3 4 6 8 Finally: 0 1 2 3 4 6 8
                 






Comments










Search Anything:

Sponsored Deals ends in





Technical Quizzes Specially For You:

Search Tags