Selection Sort VS Bubble Sort | Java program for the above approach ; Function for bubble sort ; Iterate from 1 to n - 1 ; Iterate from 0 to n - i - 1 ; Driver Code
import java . io . * ; class GFG { static void Bubble_Sort ( int [ ] arr , int n ) { boolean flag ; for ( int i = 1 ; i < n ; ++ i ) { flag = false ; for ( int j = 0 ; j <= ( n - i - 1 ) ; ++ j ) { if ( arr [ j ] > arr [ j + 1 ] ) { int temp = arr [ j ] ; arr [ j ] = arr [ j + 1 ] ; arr [ j + 1 ] = temp ; flag = true ; } } if ( flag == false ) break ; } } public static void main ( String [ ] args ) { int n = 5 ; int [ ] arr = { 2 , 0 , 1 , 4 , 3 } ; Bubble_Sort ( arr , n ) ; System . out . print ( " The ▁ Sorted ▁ Array ▁ by ▁ " + " using ▁ Bubble ▁ Sort ▁ is ▁ : ▁ " ) ; for ( int i = 0 ; i < n ; ++ i ) System . out . print ( arr [ i ] + " ▁ " ) ; } }