首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

快速排序的错误

2013-09-10 
快速排序的异常写了一个生成随机数快速排序的程序,可是总是出现异常,不知道是什么问题#include stdio.h#

快速排序的异常
写了一个生成随机数快速排序的程序,可是总是出现异常,不知道是什么问题

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define  N 30000
int CreateArray(int a[],int n)
{
int i;
if(n<0 || n>N)
return 0;
for(i=0;i<n;i++)
{
a[i]=rand();
}
printf("\n");
return 1;
}

int QkPass(int a[],int low,int high)
{
int prvotkey=a[low];
a[0]=a[low];
prvotkey=a[low];
while(low<high)
{
while(low<high && a[high]>prvotkey)
high--;
if(low<high)
{
a[low]=a[high];
low++;
}
while(low<high && a[low]<prvotkey)
low++;
if(low<high)
{
a[high]=a[low];
high--;
}
}
a[low]=a[0];
return low;
}
int QkSort(int a[],int low,int high)
{
int pos;
if(low<high)
{
pos = QkPass(a,low,high);
QkSort(a,low,pos-1);
QkSort(a,pos+1,high);
}
return 1;
}
void QuickSort(int a[],int n)
{
QkSort(a,1,n);
}



int main()
{
int a[N];
int i;
int m;
srand((unsigned) time(NULL));
printf("请输入产生随机数的个数: ");
scanf_s("%d",&m);
printf("生成的随机数为: ");
if(CreateArray(a,m))
{
for(i=0;i<m;i++)
printf("%d\t",a[i]);
printf("\n");
QuickSort(a,m+1);
printf("快速排序的结果为: \n");
for(i=0;i<m;i++)
printf("%d\t",a[i]);
}
system("pause");
}

[解决办法]
改了下 你在看下吧
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define  N 30000
int CreateArray(int a[],int n)
{
    int i;
    if(n<0 
[解决办法]
 n>N)
        return 0;
    for(i=0;i<n;i++)
    {


        a[i]=rand();
    }
    printf("\n");
    return 1;
}
 
int QkPass(int a[],int low,int high)
{
    int prvotkey=a[low];
    int tem=a[low];//用一个变量保存a[low]
    prvotkey=a[low];
    while(low<high)
    {
        while(low<high && a[high]>prvotkey)
            high--;
        if(low<high)
        {
            a[low]=a[high];
            low++;
        }
        while(low<high && a[low]<prvotkey)
            low++;
        if(low<high)
        {
            a[high]=a[low];
            high--;
        }
    }
    a[low]=tem;
    return low;
    }
int QkSort(int a[],int low,int high)
{
    int pos;
    if(low<high)
    {
        pos = QkPass(a,low,high);
        QkSort(a,low,pos-1);
        QkSort(a,pos+1,high);
    }
    return 1;
}
void QuickSort(int a[],int n)
{
    QkSort(a,0,n);//起始位置为0
}
 
 
 
int main()
{
    int a[N];
    int i;
    int m;
    srand((unsigned) time(NULL));
    printf("请输入产生随机数的个数: ");
    scanf("%d",&m);
    printf("生成的随机数为: ");
    if(CreateArray(a,m))
    {
        for(i=0;i<m;i++)
            printf("%d\t",a[i]);


        printf("\n");
        QuickSort(a,m-1);//对下表0-m-1排序
        printf("快速排序的结果为: \n");
        for(i=0;i<m;i++)
            printf("%d\t",a[i]);
    }
}

热点排行