// Optimised Bubble Sort import java.io.*; class GFG { static void bubbleSort(int arr[], int n){ boolean swapped; for(int i = 0; i < n; i++){ swapped = false; for(int j = 0; j < n - i - 1; j++){ if( arr[j] > arr[j + 1]){ // swapping int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; swapped = true; } } if(swapped == false) break; } } public static void main (String[] args) { int a[] = {2, 1, 4, 3}; bubbleSort(a, 4); for(int i = 0; i < 4; i++){ System.out.print(a[i] + " "); // OUTPUT : 1 2 3 4 } } } // Bubble Sort import java.io.*; class GFG { static void bubbleSort(int arr[], int n){ for(int i = 0; i < n; i++){ for(int j = 0; j < n - i - 1; j++){ if( arr[j] > arr[j + 1]){ // swapping int temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; } } } } public static void main (String[] args) { int a[] = {2, 1, 4, 3}; bubbleSort(a, 4); for(int i = 0; i < 4; i++){ System.out.print(a[i] + " "); // OUTPUT : 1 2 3 4 } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter