简体   繁体   中英

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

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

Corrected use: for(int i=0; i<= unsorted_index-1; i++)

Instead of: for(int i=0; i< unsorted_index-1; i++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM