hacktoberfest icon indicating copy to clipboard operation
hacktoberfest copied to clipboard

Fixed Bubble Sort Logic

Open Gorlesunilkumar opened this issue 4 months ago • 0 comments

int bubble(int arr, int n) { int i,j,temp=0,flag=0; for(i=0;i<n;i=i+1) { for(j=0;j<n-i-1;j=j+1) { if((arr+j) > *(arr+j+1)) { flag=1; temp = *(arr+j); *(arr+j) = *(arr+j+1); *(arr+j+1) = temp; } } if(flag==0) { return flag; } } }

Issue: flag was initialized only once and never reset inside the loop, so it stayed 1 after the first swap. This prevented early detection of a sorted array and caused unnecessary iterations. The function also lacked a final return, leading to undefined behavior.

Use after fix: Resets flag each pass to detect early sorting and added a final return for proper function completion and efficiency.

Gorlesunilkumar avatar Nov 06 '25 10:11 Gorlesunilkumar