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:
@ -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
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user