Difficulty: Easy
Topics: Sorting Algorithms, Iterative Methods
Companies: Commonly asked in technical interviews.
Bubble sort is a sorting algorithm that repeatedly compares adjacent elements in an array and swaps them if they are in the wrong order. This process continues until the array is completely sorted.
Bubble sort works by iteratively ensuring that, after each pass, the largest unsorted element moves to its correct position. After every iteration, the sorted portion of the array grows from right to left.
[5, 1, 4, 2, 8]
[1, 4, 2, 5, 8]
(largest element 8
bubbles up to the end).[1, 2, 4, 5, 8]
(5
bubbles up to its correct position).[1, 2, 4, 5, 8]
Advantages:
Disadvantages:
Bubble sort is primarily used for educational purposes to demonstrate the concept of sorting algorithms. For larger or more complex datasets, use more efficient algorithms like quicksort or heapsort.
Loading component...
Loading component...
INPUT: int [] arr = {4,3,2,1};
OUTPUT: arr = {1,2,3,4}
public static void main(String[] args){
int[] arr = { 64, 25, 12, 22, 11 };
System.out.print("Original array: ");
printArray(arr);
bubbleSort(arr, arr.length);
System.out.print("Sorted array: ");
printArray(arr);
} // Function End
static void bubbleSort(int arr[] , int n){
int i, j;
boolean swapped = false;
for(i =0;i<n-1; i++){
for(j =0;j<n-i-1; j++){
swapped = false;
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
swapped = true;
}//If End
}//Loop End
if(!swapped){
break;
} //If End
}//Loop End
}//function end
static void printArray(int[] arr){
for (int val : arr) {
System.out.print(val + " ");
}//Loop End
System.out.println();
} // Function End