[C語言]排序問題–我的解答

來源:互聯網
上載者:User

問題的在這裡: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;
}

其實快排還是可以進一步最佳化的。

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.