How can you improve the best case efficiency in bubble sort? (The input is already sorted)

How can you improve the best case efficiency in bubble sort? (The input is already sorted)
A.
Code:
        boolean swapped = false;
	for(int j=arr.length-1; j>=0 && swapped; j--)
	{
		swapped = true;
		for(int k=0; k<j; k++)
		{
			if(arr[k] > arr[k+1])
			{
				int temp = arr[k];
				arr[k] = arr[k+1];
				arr[k+1] = temp;
				swapped = false;
			}
		}
	}
B.
Code:
        boolean swapped = true;
	for(int j=arr.length-1; j>=0 && swapped; j--)
	{
		swapped = false;
		for(int k=0; k<j; k++)
		{
			if(arr[k] > arr[k+1])
			{
				int temp = arr[k];
				arr[k] = arr[k+1];
				arr[k+1] = temp;
			}
		}
	}
C.
Code:
        boolean swapped = true;
	for(int j=arr.length-1; j>=0 && swapped; j--)
	{
		swapped = false;
		for(int k=0; k<j; k++)
		{
			if(arr[k] > arr[k+1])
			{
				int temp = arr[k];
				arr[k] = arr[k+1];
				arr[k+1] = temp;
				swapped = true;
			}
		}
	}
D.
Code:
        boolean swapped = true;
	for(int j=arr.length-1; j>=0 && swapped; j--)
	{
		for(int k=0; k<j; k++)
		{
			if(arr[k] > arr[k+1])
			{
				int temp = arr[k];
				arr[k] = arr[k+1];
				arr[k+1] = temp;
				swapped = true;
			}
		}
	}
 
Answer: C
Explanation: A boolean variable 'swapped' determines whether any swapping has happened in a particular iteration, if no swapping has occurred, then the given array is sorted and no more iterations are required.
 

Tìm kiếm

Back
Top