题目:1. 文件"rand_3w.txt"中有三万个随机的、各不相等的正整数,写一个函数,求第k小的数。(如1、2、3、4、5,中第3小的数为3)
冒泡:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp;
unsigned int n[30000];
int i=0,j=0;
int a,flen,temp,k;
fp = fopen("rand_3w.txt","r");
if (fp == NULL)
{
printf("cannot open the file!\n");
return -1;
}
fseek(fp,0L,SEEK_END);
flen=ftell(fp);
fseek(fp,0L,SEEK_SET);
while (ftell(fp)<=flen)
{
fscanf(fp,"%d",&n[i++]);
a = ftell(fp);
fseek(fp,a+1,SEEK_SET);
}
printf("input the number:\n");
scanf("%d",&k);
while (j < k)
{
for (i=0;i<30000-j-1;i++)
{
if (n[i]<n[i+1])
{
temp = n[i];
n[i] = n[i+1];
n[i+1] = temp;
}
}
j++;
}
printf("%d\n",n[30000-k]);
return 0;
}
快排:
#include <stdio.h>
#include <stdlib.h>
int Partition(int n[],int i,int j)
{
int data=n[i];
while(i<j)
{
while (i<j && n[j]>=data)
j--;
if (i<j)
n[i++] = n[j];
while(i<j && n[i]<=data)
i++;
if (i<j)
n[j--] = n[i];
}
n[i] = data;
return i;
}
void QuickSort(int n[],int low,int high)
{
int pos;
if (low<high)
{
pos = Partition(n,low,high);
QuickSort(n,low,pos-1);
QuickSort(n,pos+1,high);
}
}
int main(void)
{
FILE *fp;
int n[30000];
int i=0;
int a,flen,k;
fp = fopen("rand_3w.txt","r");
if (fp == NULL)
{
printf("cannot open the file!\n");
return -1;
}
fseek(fp,0L,SEEK_END);
flen=ftell(fp);
fseek(fp,0L,SEEK_SET);
while (ftell(fp)<=flen)
{
fscanf(fp,"%d",&n[i++]);
a = ftell(fp);
fseek(fp,a+1,SEEK_SET);
}
printf("input the number:\n");
scanf("%d",&k);
QuickSort(n,0,30000-1);
printf("the result is %d\n",n[k-1]);
fclose(fp);
return 0;
}