Skip to main content

Posts

Showing posts with the label BubbleSort

Bubble Sort Algorithm

 Bubble sort is one of the simplest sorting algorithms.    It is a comparison-based sorting algorithm.  In this sorting algorithm, each pair of adjacent elements is compared and swapped if they are not in order.  Disadvantage:-   Not suitable for large data sets. Average and worst-case complexity = O(n^2) Normal code:- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 public class BubbleSort{ public static void main (String[] args){ int [] arr = { 3 , 2 , 5 , 4 , 7 , 9 , 1 }; for ( int i= 0 ; i<arr. length - 1 ; i++){ for ( int j= 0 ; j<arr. length - 1 -i; j++){ if (arr[j]>arr[j+ 1 ]){ int temp = arr[j]; arr[j] = arr[j+ 1 ]; arr[j+ 1 ] = temp; } } } for ( int x:arr) System. out . print (x+ " " ); } } Optim...