Skip to content

Fixed Bubble Sort Logic #774

Description

@Gorlesunilkumar

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.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions