Modified C++ Bubble sort (#19358)

Optimized by stopping the algorithm if there wasn't any swap(rest is sorted).
There was a syntax error(temp was not declared)
This commit is contained in:
UTpH
2018-10-16 00:54:33 -04:00
committed by Quincy Larson
parent 593e66ab6b
commit c614c91f8a

View File

@ -114,17 +114,20 @@ void bubblesort(int arr[], int n)
{
if(n==1) //Initial Case
return;
bool swap_flag = false;
for(int i=0;i<n-1;i++) //After this pass the largest element will move to its desired location.
{
if(arr[i]>arr[i+1])
{
temp=arr[i];
int temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
swap_flag = true;
}
}
// IF no two elements were swapped in the loop, then return, as array is sorted
if(swap_flag == false)
return;
bubblesort(arr,n-1); //Recursion for remaining array
}
```