查找算法(分割查找)
#include <stdio.h> #include <stdlib.h> #include <string.h> //顺序表查找 //从头到尾逐个比较,找到就返回下标,找不到返回0 //时间复杂度O(n) int Sequential_Search(int *array, int len, int key){ int i; array[0] = key; i = len; while(array[i] != key){ i--; } return i; } void Sequential_Sear(){ int arr[] = {0,3,2,6,5,3,7,8,1}; //注意0号元素不放实际数据,用来存放key int key = 70; int get = Sequential_Search(arr,8,key); //顺序查找 printf(" key is in %d ",get); } //end //折半查找(二分查找) //先对要查找的线性表排序,然后取中间记录比较,不符合就在中间到头(或尾)的一半查找,每次取查找区域的中间位置 //时间复杂度O(log n) //由于折半查找的前提条件需要有序表顺序存储,对于静态查找表,一次排序后不再变化,这样的算法已经比较好了。 //但对于需要频繁执行插入或删除操作的数据集来说,维护有序的排序会带来不小的工作量,就不建议使用 int Binary_Search(int *array, int len, int key){ int low,high,middle; low = 0; high = len-1; while(low <= high){ //middle = (low+high)/2; middle = low + (high - low) * (key - array[low]) / (array[high] - array[low]); if(key < array[middle]){ high = middle - 1; }else if(key > array[middle]){ low = middle + 1; }else{ return middle; } } return 0; } void Binary_Sear(){ int arr[] = {23,45,1,43,87,5,4,98,77}; int len = 9; int key = 5; //先排序 int i,j; for(i=0;i<len-1;i++){ for(j=0;j<len-i-1;j++){ if(arr[j] > arr[j+1]){ int t; t = arr[j]; arr[j] = arr[j+1]; arr[j+1] = t; } } } printf("after sort arr[]:"); for(i=0;i<len-1;i++){ printf(" %d ",arr[i]); } printf("\nkey(%d) is in %d ",key,Binary_Search(arr,len,key)); //二分查找 } //end /* 插值查找(折半查找的改进) 把middle = (low+high)/2; 改为middle = low + (high - low) * (key - array[low]) / (array[high] - array[low]); 把原来的1/2改进成(key - array[low]) / (array[high] - array[low]) 平均效率要比折半查找好的多 */ int Fibonacci_Search(int *array, int len, int key){ int F[] = {0,1,1,2,3,5,8,13,21,34,55,89}; int low,high,mid,i,k; low = 1; high = len; k = 0; while(len > F[k]-1){ k++; } for(i=len;i<F[k]-1;i++){ array[i] = array[len]; } while(low <= high){ mid = low+F[k-1]-1; if(key < array[mid]){ high = mid -1; k = k - 1; }else if(key > array[mid]){ low = mid + 1; k = k - 2; }else{ if(mid <= len){ return mid; }else{ return len; } } } return 0; } void Fibonacci_Sear(){ int arr[] = {0,23,45,1,43,87,5,4,98,77}; int len = 10; int key = 77; //先排序 int i,j; for(i=0;i<len-1;i++){ for(j=0;j<len-i-1;j++){ if(arr[j] > arr[j+1]){ int t; t = arr[j]; arr[j] = arr[j+1]; arr[j+1] = t; } } } printf("after sort arr[]:"); for(i=0;i<len;i++){ printf(" %d ",arr[i]); } printf("\nkey(%d) is in %d ",key,Fibonacci_Search(arr,len-1,key)); // } int main(){ //Sequential_Sear();//顺序查找 // Binary_Sear();//折半查找 Fibonacci_Sear(); return 0; }
本文来自博客园,作者:wzyy,转载请注明原文链接:https://www.cnblogs.com/wwzyy/p/6230920.html