函数实现对10个排好序的元素进行折半法查找

baidu_33185996 2015-12-01 02:46:40

void sort(int a[], int n);
int find(int a[], int n, int x);

#include<stdio.h>
void sort(int a[],int n)
{
int i,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]<a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}
int main()
{
int a[10]={11,12,13,14,15,16,17,18,19,20};
sort(a,10);
int i;
for(i=0;i<10;i++)
{
printf("%d\n",a[i]);
}
return 0;
}

...全文
256 点赞 收藏 4

4 条回复

visp 2015-12-01

``````
#include<stdio.h>
void print_s(int *p,int n);
int sort(int a[],int n)
{
int i,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]<a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
}

/*折半查找***************************/
int  find(int a[], int n, int x)
{
int low,high,mid;
low = 0;
high = n-1;
while (low <= high)
{
mid = (low+high)/2;

if (a[mid]>x)
low = mid+1;
else if(a[mid]<x)
high = mid-1;
else
return mid;

}
return -1;
/*****************************/
}

int main()
{
int ret;
int a[10]={11,12,13,14,15,16,17,18,19,20};
print_s(a,10);
sort(a,10);
print_s(a,10);
ret = find(a,10,17);
if (ret==-1)
printf("没找到\n");
else
printf("下标是：%d\n",ret);
//    int i;
//    for(i=0;i<10;i++)
//    {
//        printf("%d\n",a[i]);
//    }
return 0;
}

void print_s(int *p,int n)
{
int i;
for (i = 0;i<n;i++)
{
printf("%d ",*(p+i));
}
printf("\n");
}

``````

visp 2015-12-01

visp 2015-12-01

``````
#include<stdio.h>
void print_s(int *p,int n);
int sort(int a[],int n,int key)
{
int i,j;
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
print_s(a,10);

/*折半查找***************************/

int low,high,mid;
low = 0;
high = n-1;
while (low <= high)
{
mid = (low+high)/2;

if (a[mid]<key)
low = mid+1;
else if(a[mid]>key)
high = mid-1;
else
return mid;

}
return -1;
/*****************************/

}
int main()
{
int ret;
int a[10]={11,12,13,14,15,16,17,18,19,20};
print_s(a,10);
ret = sort(a,10,17);
if (ret==-1)
printf("没找到\n");
else
printf("下标是：%d\n",ret);
//    int i;
//    for(i=0;i<10;i++)
//    {
//        printf("%d\n",a[i]);
//    }
return 0;
}

void print_s(int *p,int n)
{
int i;
for (i = 0;i<n;i++)
{
printf("%d ",*(p+i));
}
printf("\n");
}

``````

C语言

6.4w+

C语言相关问题讨论

2015-12-01 02:46