Answers for "why is bubble sort the worst sorting algorithm"

0

bubble sorting

import java.util.Arrays;
public class Bubble{
	public static void main(String[] args){
		int[] arr = {5,4,3,2,1}; // Test case array
		
		for(int i =0;i<arr.length-1;i++){ // Outer Loop
		boolean swap = false;
		  for(int j =1;j<arr.length;j++){ // Inner Loop
			  if(arr[j-1]>arr[j]){ // Swapping
				  int temp = arr[j-1];
				  arr[j-1] = arr[j];
				  arr[j] = temp;
				  swap = true;
			  }
		  }
		  if(!swap){ // If you went through the whole arrray ones and 
             break; // the elements did not swap it means the array is sorted hence stop  
		  }
		}
		
		System.out.print(Arrays.toString(arr));
	}
}
Posted by: Guest on April-24-2022

Code answers related to "why is bubble sort the worst sorting algorithm"

Python Answers by Framework

Browse Popular Code Answers by Language