#include <stdio.h>
#include<stdlib.h>
#include<time.h>
void quick_sort(int a[],int low,int high);
int find_pos(int a[],int low,int high);
int* find(int a[],int n,int x);
int main(){
FILE *fp;int flen;
if((fp=fopen("numbers.txt","r"))==NULL) exit(0);
fseek(fp,0L,SEEK_END);
flen = ftell(fp);fclose(fp);
/*int fseek( FILE *stream, long offset, int origin );
重定位流(数据流/文件)上的文件内部位置指针
第一个参数stream为文件指针
第二个参数offset为偏移量,正数表示正向偏移,负数表示负向偏移
第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET
SEEK_SET: 文件开头
SEEK_CUR: 当前位置
SEEK_END: 文件结尾
其中SEEK_SET,SEEK_CUR和SEEK_END依次为0,1和2.
函数 ftell() 用于得到文件位置指针当前位置相对于文件首的偏移字节数。*/
int len = flen/4;int num[len];
int temp;int i=0;freopen("numbers.txt","r",stdin);
while(scanf("%d,",&temp)==1) num[i++] = temp;
int n = i;for(int i=0;i<n;i++) printf("%02d\t",num[i]);
printf("\n");for(int i=0;i<100;i++) printf("-");printf("\n");
quick_sort(num,0,n);
for(int i=0;i<n;i++) printf("%02d\t",num[i]);
printf("\n");for(int i=0;i<100;i++) printf("-");printf("\n");
srand( (unsigned int)(time(0)) );int exist;
printf("INPUT :%03d\t",temp=rand()%1000+1);
printf("EXIST :%03d\t",exist=find(num,n,temp)[0]);
for(int i=1;i<=exist;i++) printf("\nLOCATION :%03d",find(num,n,temp)[i]);
return 0;
}
void quick_sort(int a[],int low,int high){
if(low>=high) return;
int idx = find_pos(a,low,high);
quick_sort(a,low,idx-1);
quick_sort(a,idx+1,high);
}
int find_pos(int a[],int low,int high){
int temp = a[low];
while(low<high){
while(low<high&&a[high]>temp) high--;
a[low] = a[high];
while(low<high&&a[low]<=temp) low++;
a[high] = a[low];
}
a[low] = temp;
return low;
}
int* find(int a[],int n,int x){
int s[n+1];s[0] = x;int num[n];
for(int i=0;i<n;i++) s[i+1]=a[i];
int low = 1;int high = n;int i=0;
while(low<high){
int temp=(low+high)/2;
if(low-high==1||high-low==1) break;//查找不到时可能会在差值为1时进入死循环
if(x<s[temp]) high=temp;
else if(x>s[temp]) low=temp;
else {
num[++i] = temp;int idx=temp;
while(s[--temp]==x) num[++i]=temp;
while(s[++idx]==x) num[++i] = idx;
break;
}
}
num[0] = i;
return num;
}
折半
最新推荐文章于 2022-11-03 20:44:43 发布