Search code examples
c++sorting

Bubble sort using c


I tried to do bubble sort using c/c++. It shows the wrong output. I couldn't figure out where the bug is.

#include <stdio.h>

#define true 1
#define false 0

int main()
{
    int arr[]={26,27,2,38,44,4,19};
    int n= sizeof arr/sizeof(int);
    int swapped;
    int unsorted_index= n-1, temp;
    do{
        swapped=false;
        for(int i=0; i< unsorted_index-1; i++)
            if(arr[i]>arr[i+1])
            {
              temp=arr[i];
              arr[i]=arr[i+1];
              arr[i+1]=temp;
              swapped=true;
            }
        unsorted_index--;
      } while(swapped || unsorted_index);
    for(int i=0; i<n; i++)
       printf("%d ",arr[i]);
    return 0;
}

it shows the output: 2 4 26 27 38 44 19

instead of: 2 4 19 26 27 38 44


Solution

  • The problem is your loop is not traversing the complete array. To do this:

    Replace "unsorted_index= n-1" to "unsorted_index= n".

    output:

    2 4 19 26 27 38 44