介绍
顺序查找
按照顺序一个个查找
#include<stdio.h>
//顺序查找
int search(int arr[],int len,int aim)
{int i;for(i=0;i<len;i++){if(arr[i]==aim){return i;//返回下标 }}return -1;//表示未查询到}
int main()
{int arr[]={13,355,256,65,234,-1,35,-6,-3,-4,0};int len=sizeof(arr)/sizeof(int);//数组长度int id=search(arr,len,0);printf("查询结果:%d\n",id);if(id!=-1){printf("已找到\n");}else{printf("没有找到\n");}getchar();return 0;
}
二分查找
说明:
该数组必须是一个有序数组
思路:
方法1–while循环
//二分查找1--while循环
int binary1(int arr[],int len,int find)
{int left=0;int right=len-1;int mid=arr[(left+right)/2];while(left<=right){if(find<mid){right--;}else if(find>mid){left++;}else if(find==mid){return (left+right)/2;}mid=arr[(left+right)/2];}return -1;
}
方法2–递归
//二分查找2--递归
int binary2(int arr[],int left,int right,int find)
{int midindex=(left+right)/2;int mid=arr[midindex];if(left>right)//说明已经遍历完,未找到{return -1;}if(find<mid){binary2(arr,left,midindex-1,find);}else if(find>mid){binary2(arr,midindex+1,right,find);}else if(find==mid) {return midindex;//已找到}
}
完整代码:
#include<stdio.h>//二分查找1--while循环
int binary1(int arr[],int len,int find)
{int left=0;int right=len-1;int mid=arr[(left+right)/2];while(left<=right){if(find<mid){right--;}else if(find>mid){left++;}else if(find==mid){return (left+right)/2;}mid=arr[(left+right)/2];}return -1;
}//二分查找2--递归
int binary2(int arr[],int left,int right,int find)
{int midindex=(left+right)/2;int mid=arr[midindex];if(left>right)//说明已经遍历完,未找到{return -1;}if(find<mid){binary2(arr,left,midindex-1,find);}else if(find>mid){binary2(arr,midindex+1,right,find);}else if(find==mid) {return midindex;//已找到}
}int main()
{int arr[]={1,2,3,6,9,10,55,100,991,1000};int len=sizeof(arr)/sizeof(int);int id1=binary1(arr,len,1000);int id2=binary2(arr,0,len-1,991);printf("方法1:\n");if(id1!=-1){printf("已找到,下标为:%d\n",id1);}else{printf("未找到!\n");}printf("方法2:\n");if(id2!=-1){printf("已找到,下标为:%d\n",id2);}else{printf("未找到!\n");} getchar();return 0;
}