快速排序算法

先在D盘路径下建立一个文件夹,datafile文本文档(datafile.txt),文档内容为数序表{6,8,7,9,0,1,3,2,4,5},保存。
程序代码:(这里是快速排序算法,你可用自己的,要保证正确)
#include
#include
#include

#define MAX 100
int Partition(int a[], int low, int high )//划分
{
int i,j;
int Major_Compare = a[low];
i = low;
j = high;
while(i{
while(i{
j = j - 1;
}
if(i{
a[i] = a[j];
i=i+1;
}

while(i= a[i])
{
i = i + 1;
}
if(i{
a[j] = a[i];
j=j-1;
}

}
a[i] = Major_Compare;
return i;
}
void QuickSort(int a[], int low, int high)
{
int Position;
if(low < high)
{
Position = Partition(a,low,high);
QuickSort(a, low, Position-1);
QuickSort(a, Position+1, high);
}
}
int BinarySearch (int a[],int x,int low,int high )
{//折半搜索的递归算法
int mid = -1;
if ( low <= high ) {
mid = ( low + high ) / 2;
if ( a[mid]< x )
mid = BinarySearch (a,x,mid+1,high);
else if ( a[mid]> x )
mid = BinarySearch ( a,x,low,mid-1);
}
return mid;
}
int main(int argc, char* argv[])
{
int a[MAX];
FILE *fp;
int i = 0,n=0,k,sum=0;
char ch;
/*cout<<"请输入元素个数:";
cin>>n;
cout<if(!(fp = fopen ("D:\\datafile.txt","a")))
{
printf ("cannot open the file . \ n ");
exit (1); }
fwrite(&n,sizeof(int),1,fp);
for(i=0;i{ cin>>a[i];
fwrite(&a[i],sizeof(int),1,fp);
}*/
/* if(!(fp = fopen ("D:\\datafile8.txt","r")))
{
printf ("cannot open the file . \ n ");
exit (1); }
fread(&n,sizeof(int),1,fp);
for(i=0;i{ fread(&a[i],sizeof(int),1,fp);
cout<}*/
if((fp=fopen ("D:\\datafile.txt","r")) == NULL )/* 打开并测试文件 */
{
printf ("file cannot be opened \n");
exit (1);/* 若文件打开不成功,退出 */
}
while ((ch = fgetc(fp))!=EOF)/*读文件并测试是否文件尾 */
{
if(ch!=' ')
{ i=ch-48;
sum=sum*10+i;
}

else if(ch==' ')
{
a[n]=sum;
n++;
sum=0;
}
}
fclose (fp);/* 关闭文件 */
a[n]=sum;n++;
for(i=0;icout<QuickSort(a,0,n-1);
cout<for(i=0; i < n; i++)
cout<cout<cin>>k;
if(BinarySearch(a,k,0,n-1)==-1)
cout<<"查找失败";
else
cout<return 0;
}

结果我忘记了 ,不过最后是 0 1 2 3 4 5 6 7 8 9
我自己这里运行不出来。

相关文档
最新文档