简体   繁体   中英

Can't return the correct int in C

i'm using this function (quicksort algorithm) and im trying to get the total relocations also. In order to collect as much statitics i can i have to execute the function many times using a for loop, so after the end of the algorithm i must make the static variable equal to zero after copying it to a non-static variable and return it. Instead i always get a 0 return. Please help me to not get a 0 grade too :P Thanks

int quicksort(int left, int right, int *p)
{
    static int staticrelocations=0;
    int i,j,mid,x,temp,relocations;

    if(left<right)
    {
        i=left;
        j=right;
        mid=(left+right)/2;
        x=p[mid];
        while(i<j)
        {
            while(p[i]<x)
                i++;
            while(p[j]>x)
                j--;
            if(i<j)
            {
                if(p[i]==p[j])
                {
                    if(i<mid)
                        i++;
                    if(j>mid)
                        j--;
                }
                else
                {
                    temp=p[i];
                    p[i]=p[j];
                    p[j]=temp;
                    staticrelocations++;
                }
            }
        }
        quicksort(left,j-1,p);
        quicksort(j+1,right,p);
    }
    relocations=staticrelocations;
    staticrelocations=0;
    return relocations;
}

You recurse into quicksort() , and in the innermost invocation you set staticrelocations = 0 before returning its former value. However, in the outer quicksort() , you ignore the return value of the inner quicksort . The outer quicksort returns the zeroed staticrelocations . Instead, you should go like this:

int quicksort()
{
  int relocs = 0;
  /* function logic */
  if (/*did a new relocation*/)
    relocs++;
  relocs += quicksort(); //inner quicksort recursively
  return relocs;
}

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