Answers for "Optimized Bubble Sort"

C++
1

Optimized Bubble Sort

void bubbleSort(int *arr, int n)
{
    for(int i=0; i<n; i++)
    {
      bool flag = false;
       for(int j=0; j<n-i-1; j++)
       {
          if(array[j]>array[j+1])
          {
            flag = true;
             int temp = array[j+1];
             array[j+1] = array[j];
             array[j] = temp;
          }
       }
      // No Swapping happened, array is sorted
      if(!flag){
         return;
      }
   }
}
Posted by: Guest on October-11-2021
4

bubble sort in java

public static void bubbleSort(int arr[])
{
	for (int i = 0; i < arr.length; i++) //number of passes
    {
		//keeps track of positions per pass      
    	for (int j = 0; j < (arr.length - 1 - i); j++) //Think you can add a -i to remove uneeded comparisons 
        {
          	//if left value is great than right value 
        	if (arr[j] > arr[j + 1])
            {
              	//swap values
            	int temp = arr[j];
              	arr[j] = arr[j + 1];
              	arr[j + 1] = temp; 
            }
        }
    }
}
Posted by: Guest on April-15-2020

Browse Popular Code Answers by Language