Here's a good visualization as to what's exactly happening.
Time: O(n2) but O(n) when nearly sorted.
Space: O(1)
Bubble sort is a stable sorting algorithm.
Bubble sort has a high overhead. In the case where the given input is reversed, the algorithm will take O(n2) time.
Here's a sample implementation written in Java. Note that it extends the Sort.java class.
import java.util.Arrays;
public class BubbleSort extends Sort {
public static void main(String[] args) {
int[] testInt = {1,6,2,3,6,7,4,2,5};
bubbleSort(testInt);
System.out.println(Arrays.toString(testInt));
}
public static void bubbleSort(int[] testInt) {
/**
* If flag keeps false, then no swaps occurred, meaning
* our list is already sorted
*/
boolean flag;
do {
flag = false;
for (int j = 0; j < testInt.length-1; j++) {
if (testInt[j+1] < testInt[j]) {
swap(testInt, j, j+1);
flag = true;
}
}
} while (flag);
}
Ever feel achy from sitting crunched up on your computer table? Try lying down with these optical glasses that allow you to work on your laptop while lying flat on your back. This is the perfect solution with those with limited mobility or those who wish to prevent neck cramps and back strains.
$ Check priceLearn all the different scenarios of . This book is jam packed with code snippets written in C++ and Java to give you the edge you need to ace your technical interviews. Problems come with detailed solutions as well as a hint in case you get stuck, and organized by difficulty level with several variants to help you apply your knowledge more widely.
$ Check priceAd