[C语言]排序问题--我的解答

问题的在这里:http://www.cnblogs.com/amboyna/archive/2010/02/08/1666002.html

答案:LINUX下GCC编译通过

 

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

#define MAX 100000
int file_name = 0 ;

void merge(int nums[], int start, int new_mid, int end);
void qqsort(int a[],int low,int high);
int partions(int a[],int low,int high);
int segment(FILE *fp );


int main()
{
FILE
*fp;
//FILE *fps, *fpa, *fpb, *fpc;
fp = fopen("num.txt", "r");
segment(fp);
fclose(fp);
//printf("segment done, total:%d\n", file_name );
//return 0;

int p = 0, i = 0;
char fn[3] = "";
char ch[20] = "";
int cache[file_name];
int cmax;
int t[file_name];
FILE
*fpp[file_name];
fp
= fopen("num_b.txt", "w+");
for(; p < file_name; p++)
{
sprintf(fn,
"%d", p);
fpp[p]
= fopen(fn , "r");
if((fgets(ch, 20, fpp[p])) != NULL)
cache[p]
= atoi(ch);
}

cmax
= 0;
while(1)
{
for(p = 0; p < file_name; p++)
{
if(cache[p] > cache[cmax])
{
cmax
= p;
}
}
//printf("\n%d\n",cache[cmax]);
//sprintf(fn, "%d", cmax);

if(cache[cmax] != -1)
{
fprintf( fp,
"%d\n", cache[cmax]);
t[cmax]
++;
if((fgets(ch, 15, fpp[cmax])) != NULL)
{
cache[cmax]
= atoi(ch);
}
else
{
cache[cmax]
= -1;
}
}
else
{
fclose(fp);
char num[3];
for(p = 0; p < file_name; p++)
{
sprintf(num,
"%d", p);
remove(num);
}
return 0;
}

}


return 0;
}

int partions(int a[],int low,int high)
{
int pivotkey=a[low];
int s;
s
=a[low];
while(low<high)
{
while(low<high && a[high]<=pivotkey)
--high;
a[low]
=a[high];
while(low<high && a[low]>=pivotkey)
++low;
a[high]
=a[low];
}
a[low]
=s;
return low;
}
void qqsort(int a[],int low,int high)
{

int pivottag;
if(low<high )
{
//递归调用
pivottag=partions(a,low,high);
qqsort(a,low,pivottag
-1);
qqsort(a,pivottag
+1,high);
}
}

int write_file(FILE *fp, int nums[])
{
qqsort(nums ,
0 , MAX-1);
int c =0;
while(1)
{
fprintf( fp,
"%d\n", nums[c]);
if (++c == MAX ) return 0;
}
}

int segment(FILE *fp )
{
char ch[20];
char num[3];
int nums[MAX];
int i = 0;
FILE
* fpr ;
while(fgets(ch,100, fp) != NULL)
{
if(i <= MAX){
nums[i]
= atoi(ch);
}
else{
sprintf(num,
"%d", file_name);
fpr
= fopen( num , "w+");
write_file(fpr, nums);
fclose(fpr);
file_name
++;
i
= 0;
nums[i]
= atoi(ch);
}

i
++;
}
sprintf(num,
"%d", file_name);
fpr
= fopen( num , "w+");
write_file(fpr, nums);
fclose(fpr);
file_name
++;
return 0;
}

其实快排还是可以进一步优化的。

 

posted @ 2010-03-02 13:56  玉米疯收  阅读(1142)  评论(3编辑  收藏  举报