案例1):
1 #include <stdio.h> 2 3 int seqSearch(int arr[], int arrLen, int val){ //定义一个数组,一个数组长度,目标值 4 for (int i = 0; i < arrLen; i++){ 5 if(arr[i] == val){ 6 return i; 7 } 8 } 9 return -1; //找不到则返回-1 10 } 11 12 void main(){ 13 int arr[] = {23, 1, 34, 89, 101}; 14 int arrLen = sizeof(arr)/sizeof(int); 15 int index = seqSearch(arr, arrLen, -101); 16 if(index != -1){ 17 printf("找到,下标为%d", index); 18 }else{ 19 printf("错误,没有找到"); 20 } 21 22 }
案例2):
进行二分查找的前提:是一个有序数组!!
思路:
1 #include <stdio.h> 2 3 int binarySearch(int arr[], int leftIndex, int rightIndex, int findVal){ 4 //如果leftInde > rightIndex,说明这个数组都比较过,没有结果 5 if(leftIndex > rightIndex){ 6 return -1; 7 } 8 9 //先找到中间的数 10 int midIndex = (leftIndex + rightIndex)/2; //此时leftIndex=0,rightIndex=5,最后结果为2(精度丢失) 11 int midVal = arr[midIndex]; //arr[2]=10 12 //进行比较 13 if(midVal > findVal){ //如果midVal > findVal,说明要在midVal的左边查找 14 binarySearch(arr, leftIndex, midIndex-1, findVal); 15 }else if(midVal < findVal){ //如果midVal < findVal,说明要在midVal的右边查找 16 binarySearch(arr, midIndex+1, rightIndex, findVal); 17 }else{ 18 return midIndex; //返回改数的下标 19 } 20 } 21 22 void main(){ 23 int arr[] = {1, 8, 10, 89, 1000, 1234}; 24 int arrLen = sizeof(arr)/sizeof(int); 25 int index = binarySearch(arr, 0, arrLen-1, 89); 26 if(index != -1){ 27 printf("index = %d", index); 28 }else{ 29 printf("没有找到"); 30 } 31 }标签:二分,index,arr,顺序,int,findVal,查找,midVal,rightIndex From: https://www.cnblogs.com/MorningMaple/p/16769816.html