简体   繁体   中英

Bubble sort program in c

I wrote the following code for a bubble sort program in c: http://pastebin.com/Jtcpn59U

However, the bubblesort function does not seem to be working. Once I enter the array values as prompted by the getArray() function the program goes idle. Does anyone know what is going wrong?

Pay attention to this part of program :

for(i=0;i<n;i++)
 {
            if(a[i]>a[i+1])
            {
                           temp=a[i];
                           a[i]=a[i+1];
                           a[i+1]=temp;
            }
 }

When you are writing if(a[i]>a[i+1]) , a[i+1] seeks for position that does not exists! Just limit your for loop to less than n-1 :

for(i=0;i<n-1;i++)

Instead of for(i=0;i<n;i++)

Hope, this will work! :)

 bool flag, i;
 flag=TRUE;
 for(i=0;i<n;i++)
 {
     if(a[i]>a[i+1])
     flag=FALSE;
 }

The bool type is large enough to store the values 0 or 1 but your are using your i object as an index variable.

Then in bubbleSort function:

 for(i=0;i<n;i++)
 {
     if(a[i]>a[i+1])
     {
         temp=a[i];
         a[i]=a[i+1];
         a[i+1]=temp;
     }
 }

When i is n - 1 you are accessing a[n - 1] and a[n] but a[n] is outside your array. Remember arrays are 0 -origin: your last array element is a[n - 1]

bubbleSort() itself has an illegal memory access since the loop variable i is from 0 to n-1, but you access a[i+1] . but that would not cause it to sit idle.

the same issue occurs in isordered() and may cause it always to return FALSE - that could the cause of your unlimited recursion.

to fix the two issues above, reduce the loop limits to n-1 wherever you access i+1 inside the loop. to see the error yourself, run with valgrind (ie if it is installed on your machine, do valgrind a.out replacing a.out with whatever your program is called).

isordered() should end with return flag instead of the silly tests.

ouah's point (that you are making the loop counter bool instead of int ) is also valid.

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