// 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
}
}
}
star

Tue Feb 08 2022 14:45:51 GMT+0000 (Coordinated Universal Time)

#java #gfg #geeksforgeeks #lecture #sorting #bubblesort