Implement Bubble Sort using Java
If you’re in a computer science background, widening your technical horizons is the best thing you should do. However, your programming skills matter the most and one must continuously keep sharpening these skills, to become a better programmer in the future. Though there are multiple things to focus on, one specific area you must focus on is the world of data structures. Data structures in general are specific approaches to solve problems in such a way that computer resources get used minimum. In general, there are multiple data structures you can learn and implement as well. However, to keep things simple were going to start with some basic programs you must learn before moving on to complex algorithms. Therefore today we’re going to learn how to Implement Bubble Sort using Java.
What is Bubble Sort?
- Comes in the list of simplest data structures, Bubble Sort is the way of arranging elements in ascending order. The array is either sorted or is unsorted.
- Works by comparing adjacent elements in an array and swapping them, if required. This process continues till each element in an array gets sorted.
What’s The Approach?
- Consider array,
arr[n]
of sizen
we want to implement Bubble Sort on. So firstly we’ll iterate afor
loop, with an iterative variablei
from0 to n-1
.
- Next, inside the previous for loop, we’ll iterate a new for loop, with an iterative variable
j
from0 to n-i-1
.
- we’ll compare the element at iterating index with its next element from the array. If the comparing element is smaller, we’ll swap the elements.
Also Read: Implement Linked List using Java
Java Program To Implement Bubble Sort
Input:
64, 34, 25, 12, 22, 11, 90
Output:
Sorted array:
11 12 22 25 34 64 90
// Java program for implementation of Bubble Sort class TechDecodeTutorials { //Bubble Sort Function void bubbleSort(int arr[]) { int n = arr.length; for (int i = 0; i < n-1; i++) for (int j = 0; j < n-i-1; j++) if (arr[j] > arr[j+1]) { // swap arr[j+1] and arr[j] int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } /* Prints the array */ void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { TechDecodeTutorials TDT = new TechDecodeTutorials(); int arr[] = {64, 34, 25, 12, 22, 11, 90}; TDT.bubbleSort(arr); System.out.println("Sorted array"); TDT.printArray(arr); } }