user466534
user466534

Reputation:

multikey quicksort crashes

i am writing multikey quicksort,i compiles fine,but when i run ,stops working abnormaly,i think it loops for ever or something like this,how could i fix this?ones again when compile no problem,here is link for it http://ideone.com/bBtaX

it writes runtime error,here is also code

#include<stdlib.h>
#include<stdio.h>
#include<string.h>
#include<iostream>

using namespace std;

int min(int a,int b){
    return a<=b?a:b;
}

#define swap(a,b){ char *t=x[a];x[a]=x[b];x[b]=t;}
#define i2c(i)  x[i][depth]

void vecswap(int i, int j, int n, char *x[])
{ 
    while (n-- > 0) {
        swap(i, j);
        i++;
        j++;
    }
}

void ssort1(char *x[],int n,int depth);

void  ssort(char *x[],int n)
{
    ssort1(x,n,0);
}

void ssort1(char *x[],int n,int depth){
    int a,b,c,d,r,v;
    if(n<=1)
        return ;
    a=rand()%n;
    swap(0,a);
    v=i2c(0);
    a=b=1;
    c=d=n-1;
    for (;;)
    {
        while(b<=c && (r=i2c(b)-v)<=0){
            if (r==0) { 
                swap(a,b);a++;
            }
            b++;
        }

        while(b<=c && (r=i2c(c)-v)>=0){
            if (r==0) { 
                swap(c,d); d--;
            }
            c--;
        }

        if (b>c)  
            break;
        swap(b,c);
        b++;
        c--;
    }
    r=min(a,b-a);
    vecswap(0,b-r,r,x);
    r = min(d-c, n-d-1); 
    vecswap(b, n-r, r, x);
    r=b-a;
    ssort1(x,r,depth);
    if (i2c(r)!=0)
        ssort1(x+r,a+n-d-1,depth+1);
    r=d-c; 
    ssort1(x+n-r,r,depth);
}

int main(){
    char *s[]={"dato","giorgi","beso","computer","deda","kata","spilo"};
    int n=sizeof(s)/sizeof(char);

    ssort(s,n);
    for (int i=0;i<n;i++)
        cout<<s[i]<<"  "<<endl;
    return 0;
}

Upvotes: 0

Views: 290

Answers (1)

hmjd
hmjd

Reputation: 121961

This:

int n=sizeof(s)/sizeof(char); /* Would return 28, resulting in out of bounds
                                 on array 's' in subsequent for loop. */

should be:

int n=sizeof(s)/sizeof(char*);
                           ^

A safer way of determining the number of elements in an array is:

int n=sizeof(s)/sizeof(s[0]);

Upvotes: 2

Related Questions