Bubble Sort is the start sorting algorithm I learned during my college day, as well as later thus many years it's the ane I shout out back past times heart. It's form of weird that ane of the most pop sorting algorithm is likewise ane of the worst performing sorting algorithm. Bubble sort's average instance functioning is inwards O(n^2), which agency every bit the size array grows, the fourth dimension it convey to sort that array increases quadratic. Due to this reason, bubble sort is non used inwards production code, instead quick sort as well as merge sort are preferred over it. In fact, Java's ain Arrays.sort() method, which is the easiest way to sort an array inwards Java likewise uses ii pin quicksort to sort primitive array as well as stable mergesort algorithm to sort object arrays.
The argue of ho-hum functioning of this algorithm is excessive comparing as well as swapping, since it compare each chemical constituent of array to around other as well as swaps if it is on right side.
Due to quadratic performance, bubble sort is best suited for small, almost sorted listing e.g. {1, 2, 4, 3, 5} , where it simply require to produce ane swapping. Ironically, best instance functioning of bubble sort, which is O(n) beats quicksort's best instance functioning of O(NlogN).
Someone may fence that why pedagogy an algorithm which that pitiful performance, why non instruct insertion or alternative sort which is every bit piece of cake every bit bubble sort, as well as performs better. IMHO, easiness of algorithm depends upon programmer every bit much every bit on algorithm itself.
Many programmer volition discover insertion sort easier than bubble sort but in ane lawsuit again at that spot volition live a lot many who volition discover bubble sort easier to remember, including myself. This is true, despite many of them conduct hold used insertion sort unknowingly inwards existent life, e.g. sorting playing cards inwards hand.
Another argue for learning this sorting algorithm is for comparative analysis, how y'all improve algorithms, how y'all come upwards up alongside unlike algorithms for same problems. In short, despite of all its shortcomings, bubble sort is even thus the most pop algorithm.
In this tutorial, nosotros volition acquire how bubble sort works, complexity as well as functioning of bubble sort algorithm, implementation as well as source code inwards Java as well as a measuring past times measuring instance of bubble sort.
In this array, nosotros start from index 0, which is five as well as starts comparing elements from start to end. So start chemical constituent nosotros compare five is 1, as well as since five is greater than 1 nosotros swap them ( because ascending guild sorted array volition conduct hold larger divulge towards end). Next nosotros compare five to 6, hither no swapping because half dozen is greater than five as well as it's on higher index than 5. Now nosotros compare half dozen to 2, in ane lawsuit again nosotros require swapping to displace half dozen towards end. At the cease of this locomote past times half dozen reaches (bubbles up) at the top of the array. In side past times side iteration five volition live sorted on its seat as well as later n iteration all elements volition live sorted. Since nosotros compare each chemical constituent alongside another, nosotros require ii for loops as well as that final result inwards complexity of O(n^2).
Here nosotros conduct hold integer array {9, 7, 3, 6, 2} as well as start alongside 4 variable i, j, temp as well as array length which is stored inwards variable n. We conduct hold ii for loop, outer loop runs from 1 to n-1. Our inner loop runs from n-1 to i. Many programmer brand error here, if y'all start outer loop alongside minute chemical constituent than brand certain to utilization j>=i status on inner loop, or if y'all start alongside start chemical constituent e.g. i=0, brand certain y'all utilization j>i to avoid ArrayIndexOutOfBound exception. Now nosotros compare each chemical constituent as well as swap them to displace smaller chemical constituent towards forepart of array. As I said depending upon your navigation administration either largest chemical constituent volition live sorted at highest index inwards start locomote past times or smallest chemical constituent volition live placed inwards lowest index. In this case, later start pass, smallest divulge volition live sorted. This loop runs until j>=i later than it finishes as well as i becomes i + 1. This whole procedure repeats until outer loop is finished as well as that fourth dimension your array is sorted. In flowchart, a diamond box is used for determination making, which is equivalent of if-else disputation inwards code. You tin come across hither determination box is within inner loop, which agency nosotros produce N comparing inwards each iteration, totals to NxN comparisons.
Bubble sort Worst instance functioning O(n^2)
Bubble sort Best instance functioning O(n)
Bubble sort Average instance functioning O(n^2)
You tin farther explore insertion sort as well as alternative sort, which likewise does sorting inwards similar fourth dimension complexity. By the y'all tin non exclusively sort the array using bubble sort but ArrayList or whatever other collection shape every bit well. Though y'all should actually utilization Arrays.sort() or Collections.sort() for those purpose.
Now let's bear witness this method for ii input, ane inwards which array is sorted (best case) as well as other on which exclusively ane duad is out of order. If nosotros locomote past times int array {10, 20, 30, 40, 50, 60} to this method, initially volition expire within piece loop as well as brand swapped=false. Then it volition expire within for loop. when i =0 it volition compare number[i] to number[i+1] i.e. 10 to twenty as well as cheque if 10 > 20, since it's non it volition non expire within if block as well as no swapping volition live occurred. When i=1, it volition compare twenty > xxx in ane lawsuit again no swapping, side past times side when i =2 30> forty which is faux thus no telephone commutation again, side past times side i =3 thus 40> 50, which is in ane lawsuit again false, thus no swapping. Now terminal duad comparing i=4, it volition compare 50 > 60 in ane lawsuit again this is false, thus command volition non expire within if block as well as no telephone commutation volition live made. Because of that swapped volition rest faux as well as command volition non expire within piece loop again. So y'all know that your array is sorted simply later ane pass.
Now see around other example, where simply ane duad is out of order, let's state String array names = {"Ada", "C++", "Lisp", "Java", "Scala"}, hither exclusively ane duad is out of guild e.g. "Lisp" should come upwards later "Java". Let's come across how our improved bubble sort algorithm function here. In start pass, comparing volition maintain without telephone commutation until nosotros compare "Lisp" to "Java", hither "Lisp".compareTo("Java") > 0 volition expire truthful as well as swapping volition occur, which agency Java volition expire to the Lisp place, as well as Lisp volition convey Java's place. this volition brand boolean variable swapped=true, Now inwards terminal comparing on this pass, nosotros compare "Lisp" to "Scala" as well as in ane lawsuit again no exchange. Now nosotros volition trim down terminal index past times 1 because Scala is sorted at terminal seat as well as volition non participate further. But at in ane lawsuit swapped variable is true, thus command volition in ane lawsuit again expire within piece loop, as well as for loop but this fourth dimension no exchanged volition live made thus it volition non convey around other pass. Our array is at in ane lawsuit sorted inwards simply ii locomote past times compared to N-1 locomote past times of before implementation. This bubble sort implementation is much amend as well as fifty-fifty perform amend than Selection sort algorithm inwards average instance because, at in ane lawsuit sorting is non proportional to total divulge of elements but exclusively alongside divulge of pairs which are out-of-order.
By the way to sort String array using Bubble Sort, y'all require to overload BubbleSortImproved() method to convey String[] as well as likewise require to utilization compareTo() method to compare ii String object lexicographically. Here is Java programme to sort String array using Bubble Sort :
That's all most Bubble Sort inwards Java. We conduct hold learned how bubble sort algorithm works as well as how produce y'all implement it inwards Java. As I said, it is ane of the simplest sorting algorithm as well as real piece of cake to remember, but likewise it doesn't conduct hold whatever practical utilization apart from academics as well as inwards information construction as well as algorithm preparation classes. It's worst instance functioning is quadratic which agency it non suitable for large array or list. If y'all conduct hold to utilization bubble sort, it's best suited for small, already sorted array inwards which instance it has to real few swapping as well as it's functioning is inwards O(n). If y'all dear algorithms, y'all tin come across this employment of finding wheel on linked list.
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part 1 as well as 2
The argue of ho-hum functioning of this algorithm is excessive comparing as well as swapping, since it compare each chemical constituent of array to around other as well as swaps if it is on right side.
Due to quadratic performance, bubble sort is best suited for small, almost sorted listing e.g. {1, 2, 4, 3, 5} , where it simply require to produce ane swapping. Ironically, best instance functioning of bubble sort, which is O(n) beats quicksort's best instance functioning of O(NlogN).
Someone may fence that why pedagogy an algorithm which that pitiful performance, why non instruct insertion or alternative sort which is every bit piece of cake every bit bubble sort, as well as performs better. IMHO, easiness of algorithm depends upon programmer every bit much every bit on algorithm itself.
Many programmer volition discover insertion sort easier than bubble sort but in ane lawsuit again at that spot volition live a lot many who volition discover bubble sort easier to remember, including myself. This is true, despite many of them conduct hold used insertion sort unknowingly inwards existent life, e.g. sorting playing cards inwards hand.
Another argue for learning this sorting algorithm is for comparative analysis, how y'all improve algorithms, how y'all come upwards up alongside unlike algorithms for same problems. In short, despite of all its shortcomings, bubble sort is even thus the most pop algorithm.
In this tutorial, nosotros volition acquire how bubble sort works, complexity as well as functioning of bubble sort algorithm, implementation as well as source code inwards Java as well as a measuring past times measuring instance of bubble sort.
How Bubble Sort Algorithm works
If y'all are the ane who focus on names, as well as then y'all mightiness conduct hold got an thought how bubble sort works. Just similar a bubble comes upwards from water, inwards bubble sort smallest or largest number, depending upon whether y'all are sorting array on ascending or descending order, bubbles upwards towards start or cease of the array. We require at to the lowest degree north locomote past times to sort the array completely as well as at the cease of each locomote past times ane elements are sorted inwards its proper position. You tin convey start chemical constituent from array, as well as start comparing it alongside other element, swapping where it's lesser than the divulge y'all are comparing. You tin start this comparing from start or from end, every bit nosotros conduct hold compared elements from cease inwards our bubble sort example. It is said that a motion painting is worth to a greater extent than than a grand discussion as well as it's specially truthful inwards instance of agreement sorting algorithm. Let' come across an step past times measuring instance to sort array using bubble sort, every bit I said later each locomote past times largest divulge is sorted.In this array, nosotros start from index 0, which is five as well as starts comparing elements from start to end. So start chemical constituent nosotros compare five is 1, as well as since five is greater than 1 nosotros swap them ( because ascending guild sorted array volition conduct hold larger divulge towards end). Next nosotros compare five to 6, hither no swapping because half dozen is greater than five as well as it's on higher index than 5. Now nosotros compare half dozen to 2, in ane lawsuit again nosotros require swapping to displace half dozen towards end. At the cease of this locomote past times half dozen reaches (bubbles up) at the top of the array. In side past times side iteration five volition live sorted on its seat as well as later n iteration all elements volition live sorted. Since nosotros compare each chemical constituent alongside another, nosotros require ii for loops as well as that final result inwards complexity of O(n^2).
FlowChart of Bubble Sort Algorithm
Another cool way to sympathise an algorithm is to depict it's flowchart. It volition walk through each iteration inwards loop as well as how decisions are made during algorithm execution. Here is flowchart of our bubble sort algorithm, which complements our implementation of this sorting algorithm.Here nosotros conduct hold integer array {9, 7, 3, 6, 2} as well as start alongside 4 variable i, j, temp as well as array length which is stored inwards variable n. We conduct hold ii for loop, outer loop runs from 1 to n-1. Our inner loop runs from n-1 to i. Many programmer brand error here, if y'all start outer loop alongside minute chemical constituent than brand certain to utilization j>=i status on inner loop, or if y'all start alongside start chemical constituent e.g. i=0, brand certain y'all utilization j>i to avoid ArrayIndexOutOfBound exception. Now nosotros compare each chemical constituent as well as swap them to displace smaller chemical constituent towards forepart of array. As I said depending upon your navigation administration either largest chemical constituent volition live sorted at highest index inwards start locomote past times or smallest chemical constituent volition live placed inwards lowest index. In this case, later start pass, smallest divulge volition live sorted. This loop runs until j>=i later than it finishes as well as i becomes i + 1. This whole procedure repeats until outer loop is finished as well as that fourth dimension your array is sorted. In flowchart, a diamond box is used for determination making, which is equivalent of if-else disputation inwards code. You tin come across hither determination box is within inner loop, which agency nosotros produce N comparing inwards each iteration, totals to NxN comparisons.
Complexity as well as Performance of Bubble Sort Algorithm
As I said before compared to other sorting algorithm similar quicksort, merge sort or shell sort, bubble sort performs poorly. These algorithm has average instance complexity of O(NLogN), piece average instance complexity of bubble sort O(n^2). Ironically inwards best instance bubble sort produce amend than quicksort alongside O(n) performance. Bubble sort is 3 times slower than quicksort or mergesort fifty-fifty for n = 100 but it's easier to implement as well as remember. hither is the summary of bubble sort functioning as well as complexity :Bubble sort Worst instance functioning O(n^2)
Bubble sort Best instance functioning O(n)
Bubble sort Average instance functioning O(n^2)
You tin farther explore insertion sort as well as alternative sort, which likewise does sorting inwards similar fourth dimension complexity. By the y'all tin non exclusively sort the array using bubble sort but ArrayList or whatever other collection shape every bit well. Though y'all should actually utilization Arrays.sort() or Collections.sort() for those purpose.
Bubble Sort Implementation inwards Java
hither is the Java programme to implement bubble sort algorithm using Java programming language. Don't surprise alongside import of java.util.Array, nosotros conduct hold non used it's sort method here, instead it is used to print arrays inwards readable format. I conduct hold created a swap role to swap numbers as well as improve readability of code, if y'all don't similar y'all tin in-line the code inwards the swap method within if disputation of inner loop. Though I conduct hold used principal method for testing, every bit it demonstrate better, I would propose y'all to write around unit of measurement bear witness instance for your bubble sort implementation. If y'all don't know how to produce that, y'all tin come across this JUnit tutorial.import java.util.Arrays; /** * Java programme to implement bubble sort algorithm as well as sort integer array using * that method. * * @author Javin Paul */ public class BubbleSort{ public static void main(String args[]) { bubbleSort(new int[] { 20, 12, 45, 19, 91, 55 }); bubbleSort(new int[] { -1, 0, 1 }); bubbleSort(new int[] { -3, -9, -2, -1 }); } /* * This method sort the integer array using bubble sort algorithm */ public static void bubbleSort(int[] numbers) { System.out.printf("Unsorted array inwards Java :%s %n", Arrays.toString(numbers)); for (int i = 0; i < numbers.length; i++) { for (int j = numbers.length -1; j > i; j--) { if (numbers[j] < numbers[j - 1]) { swap(numbers, j, j-1); } } } System.out.printf("Sorted Array using Bubble sort algorithm :%s %n", Arrays.toString(numbers)); } /* * Utility method to swap ii numbers inwards array */ public static void swap(int[] array, int from, int to){ int temp = array[from]; array[from] = array[to]; array[to] = temp; } } Output Unsorted array inwards Java : [20, 12, 45, 19, 91, 55] Sorted Array using Bubble sort algorithm : [12, 19, 20, 45, 55, 91] Unsorted array inwards Java : [-1, 0, 1] Sorted Array using Bubble sort algorithm : [-1, 0, 1] Unsorted array inwards Java : [-3, -9, -2, -1] Sorted Array using Bubble sort algorithm : [-9, -3, -2, -1]
How to improve Bubble Sort Algorithm
In interview ane of the pop follow-up query is how produce y'all improve a detail algorithm, as well as Bubble Sort is no unlike than that. If y'all wrote bubble sort similar the ane nosotros conduct hold shown here, interviewer volition definitely going to inquire most how produce y'all improve your bubble sort method. In guild to improve whatever algorithm, y'all must sympathise how each measuring of that algorithm works, as well as then exclusively y'all volition live able to spot whatever deficiency inwards code. If y'all follow the tutorial, y'all volition discover that array is sorted past times moving elements to their right position. In worst instance province of affairs if array is contrary sorted as well as then nosotros require to displace every element, this volition require n-1 passes, n-1 comparing inwards each locomote past times as well as n-1 exchanges, but how most best instance if array is already sorted, our existing bubble sort method is even thus going to convey n-1 pass, same divulge of comparing but no exchange. If y'all discover carefully, y'all volition discover that later ane locomote past times through the array, the largest chemical constituent volition moved to the cease of the array, but many other elements likewise moved toward their right positions, every bit bubbles displace toward the water’s surface. By leveraging this property, y'all tin deduce that during a pass, if no duad of consecutive entries is out of order, as well as then the array is sorted. Our electrical flow algorithm is non taking payoff of this property. If nosotros rail exchanges as well as then nosotros tin create upwards one's hear whether additional iteration over array is needed or not. Here is an improved version of Bubble Sort algorithm, which volition exclusively convey 1 iteration as well as n-1 comparing inwards best case, when array is already sorted. This volition likewise improve Bubble sort's average instance performance, every bit compared to our existing method which volition ever convey north - 1 passes./* * An improved version of Bubble Sort algorithm, which volition exclusively produce * 1 locomote past times as well as n-1 comparing if array is already sorted. */ public static void bubbleSortImproved(int[] number) { boolean swapped = true; int terminal = number.length - 2; // exclusively maintain if swapping of divulge has occurred while (swapped) { swapped = false; for (int i = 0; i <= last; i++) { if (number[i] > number[i + 1]) { // duad is out of order, swap them swap(number, i, i + 1); swapped = true; // swapping occurred } } // later each locomote past times largest chemical constituent moved to cease of array last--; } }
Now let's bear witness this method for ii input, ane inwards which array is sorted (best case) as well as other on which exclusively ane duad is out of order. If nosotros locomote past times int array {10, 20, 30, 40, 50, 60} to this method, initially volition expire within piece loop as well as brand swapped=false. Then it volition expire within for loop. when i =0 it volition compare number[i] to number[i+1] i.e. 10 to twenty as well as cheque if 10 > 20, since it's non it volition non expire within if block as well as no swapping volition live occurred. When i=1, it volition compare twenty > xxx in ane lawsuit again no swapping, side past times side when i =2 30> forty which is faux thus no telephone commutation again, side past times side i =3 thus 40> 50, which is in ane lawsuit again false, thus no swapping. Now terminal duad comparing i=4, it volition compare 50 > 60 in ane lawsuit again this is false, thus command volition non expire within if block as well as no telephone commutation volition live made. Because of that swapped volition rest faux as well as command volition non expire within piece loop again. So y'all know that your array is sorted simply later ane pass.
Now see around other example, where simply ane duad is out of order, let's state String array names = {"Ada", "C++", "Lisp", "Java", "Scala"}, hither exclusively ane duad is out of guild e.g. "Lisp" should come upwards later "Java". Let's come across how our improved bubble sort algorithm function here. In start pass, comparing volition maintain without telephone commutation until nosotros compare "Lisp" to "Java", hither "Lisp".compareTo("Java") > 0 volition expire truthful as well as swapping volition occur, which agency Java volition expire to the Lisp place, as well as Lisp volition convey Java's place. this volition brand boolean variable swapped=true, Now inwards terminal comparing on this pass, nosotros compare "Lisp" to "Scala" as well as in ane lawsuit again no exchange. Now nosotros volition trim down terminal index past times 1 because Scala is sorted at terminal seat as well as volition non participate further. But at in ane lawsuit swapped variable is true, thus command volition in ane lawsuit again expire within piece loop, as well as for loop but this fourth dimension no exchanged volition live made thus it volition non convey around other pass. Our array is at in ane lawsuit sorted inwards simply ii locomote past times compared to N-1 locomote past times of before implementation. This bubble sort implementation is much amend as well as fifty-fifty perform amend than Selection sort algorithm inwards average instance because, at in ane lawsuit sorting is non proportional to total divulge of elements but exclusively alongside divulge of pairs which are out-of-order.
By the way to sort String array using Bubble Sort, y'all require to overload BubbleSortImproved() method to convey String[] as well as likewise require to utilization compareTo() method to compare ii String object lexicographically. Here is Java programme to sort String array using Bubble Sort :
import java.util.Arrays; class BubbleSortImproved { public static void main(String args[]) { String[] bear witness = {"Ada", "C++", "Lisp", "Java", "Scala"}; System.out.println("Before Sorting : " + Arrays.toString(test)); bubbleSortImproved(test); System.out.println("After Sorting : " + Arrays.toString(test)); } /* * An improved implementation of Bubble Sort algorithm, which volition exclusively produce * 1 locomote past times as well as n-1 comparing if array is already sorted. */ public static void bubbleSortImproved(String[] names) { boolean swapped = true; int terminal = names.length - 2; // exclusively maintain if swapping of divulge has occurred while (swapped) { swapped = false; for (int i = 0; i <= last; i++) { if (names[i].compareTo(names[i + 1]) > 0) { // duad is out of order, swap them swap(names, i, i + 1); swapped = true; // swapping occurred } } // later each locomote past times largest chemical constituent moved to cease of array last--; } } public static void swap(String[] names, int fromIdx, int toIdx) { String temp = names[fromIdx]; // exchange names[fromIdx] = names[toIdx]; names[toIdx] = temp; } } Output: Before Sorting : [Ada, C++, Lisp, Java, Scala] After Sorting : [Ada, C++, Java, Lisp, Scala]
Which ane is amend Selection Sort vs Bubble Sort?
Though both Selection Sort as well as Bubble sort has complexity of O(n^2) inwards worst case. On average, nosotros hold off the bubble sort to perform amend than Selection sort, because bubble sort volition destination sorting sooner than the alternative sort due to to a greater extent than information movements for the same divulge of comparisons, because we compare elements inwards duad on Bubble Sort. If nosotros utilization our improved implementation Bubble Sort as well as then a boolean bear witness to non displace into on piece loop when array gets sorted volition likewise help. As I said, The worst instance of the bubble sort happens when the master array is inwards descending order, piece inwards best case, if the master array is already sorted, the bubble sort volition perform exclusively ane locomote past times whereas the alternative sort volition perform north - 1 passes. Given this, I think on average Bubble sort is amend than Selection sort.That's all most Bubble Sort inwards Java. We conduct hold learned how bubble sort algorithm works as well as how produce y'all implement it inwards Java. As I said, it is ane of the simplest sorting algorithm as well as real piece of cake to remember, but likewise it doesn't conduct hold whatever practical utilization apart from academics as well as inwards information construction as well as algorithm preparation classes. It's worst instance functioning is quadratic which agency it non suitable for large array or list. If y'all conduct hold to utilization bubble sort, it's best suited for small, already sorted array inwards which instance it has to real few swapping as well as it's functioning is inwards O(n). If y'all dear algorithms, y'all tin come across this employment of finding wheel on linked list.
Further Learning
The Coding Interview Bootcamp: Algorithms + Data Structures
Data Structures as well as Algorithms: Deep Dive Using Java
Algorithms as well as Data Structures - Part 1 as well as 2