我正在编写多键快速排序,我编译得很好,但是当我运行时,停止工作异常,我认为它永远循环或类似的东西,我怎么能解决这个问题?再次编译时没有问题,这里是链接它 http://ideone.com/bBtaX
它写了运行时错误,这里也是代码
#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;
}
答案 0 :(得分:2)
此:
int n=sizeof(s)/sizeof(char); /* Would return 28, resulting in out of bounds
on array 's' in subsequent for loop. */
应该是:
int n=sizeof(s)/sizeof(char*);
^
确定数组中元素数量的更安全的方法是:
int n=sizeof(s)/sizeof(s[0]);