In this tutorial, We are going to learn bubble sort algorithm and it’s implementation in java. We are going to discuss following points in this tutorial.
i) Bubble Sort Algorithm.
ii) Bubble sort program in java (How we can sort an unsorted array using bubble sort algorithm).
iii) Bubble sort video tutorial.
Bubble Sort
* Bubble sort is a very basic and simple sorting algorithm which sort an unsorted array.
* It works by comparing each pair of adjacent element and swap them if they are in a wrong order.
* The time complexity of Bubble sort is O(n2).
* Bubble sort is not efficient for large data set.
Sorting algorithms and their time complexities
Insertion Sort Program in Java
Bubble Sort Program in Java
We have discussed how bubble sort algorithm works. Let’s write a java program to implement Bubble Sort.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
/* * Bubble Sort Algorithm Implementation in Java */ public class BubbleSort { public static void main(String[] args) { int arr[] = { 6, 4, 1, 2, 5}; for(int i = 0; i < arr.length-1; i++) { for(int j = 0; j < arr.length-1-i; j++) { //Logic to swap element if(arr[j] > arr[j+1]) { int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } for(int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } |
Bubble Sort Video Tutorial
In this video tutorial, I have explained how bubble sort works through example.