欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++实现顺序查找、折半查找、插值查找和斐波那契查找四种查找方式

程序员文章站 2022-07-12 09:47:47
...
#include<stdlib.h>
#include<iostream>

using namespace std;

//四种查找方式函数声明
int seqSearch(int *array,int low,int high,int key);
int binarySearch(int* array, int low, int high, int key);
int interpolationSearch(int* array, int low, int high, int key);
int FibonacciSearch(int* array, int n, int key);

//斐波那契数列的生成函数
int Fibonacci(int n);


//主函数来调用四种查找方式
int main()
{
	int* array = new int[100];
	int low = 1;
	int high = 7;

	array[1] = 2;
	array[2] = 3;
	array[3] = 7;
	array[4] = 10;
	array[5] = 14;
	array[6] = 17;
	array[7] = 23;
	int seqResult = seqSearch(array,low,high,10);
	cout << "顺序结果:" << seqResult << endl;
	int binaryResult = binarySearch(array,low,high,10);
	cout << "二分查找结果:" << binaryResult << endl;
	int interpolationResult = interpolationSearch(array, low, high, 10);
	cout << "插值查找结果:" << interpolationResult << endl;
	int FibonacciResult = FibonacciSearch(array,7,10);
	cout << "斐波那契查找结果:" << FibonacciResult << endl;
	return 0;
}

//顺序查找函数定义
int seqSearch(int* array, int low, int high, int key)
{
	for (int i = low; i < high; i++)
	{
		if (array[i] == key)
		{
			return i;
		}
	}
	return -1;
}


//折半查找函数定义
int binarySearch(int *array,int low,int high,int key)
{

	while (low <= high)
	{
		int mid = (low + high) / 2;
		if (key == array[mid])
		{
			return mid;
		}
		else if (key > array[mid])
		{
			low = mid + 1;
		}
		else
		{
			high = mid - 1;
		}
	}

	return -1;
}


//插值查找函数定义
int interpolationSearch(int* array, int low, int high, int key)
{
	while (low <= high)
	{
		int mid = low + (key-array[low])/(array[high]-array[low])*(high-low);
		if (key == array[mid])
		{
			return mid;
		}
		else if (key>array[mid])
		{
			low = mid + 1;
		}
		else
		{
			high = mid - 1;
		}
	}
	return 0;
}


//斐波那契函数定义
int FibonacciSearch(int* array, int n, int key)
{
	int low, high, mid, i, k;
	low = 1;
	high = n;
	k = 0;
	while (n>Fibonacci(k)-1)
	{
		k++;
	}
	for ( i = n; i < Fibonacci(k)-1; i++)
	{
		array[i] = array[n];
	}

	while (low<=high)
	{
		mid = low + Fibonacci(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 <= n)
			{
				return mid;
			}
			else
			{
				return n;
			}
		}
	}
	return 0;
}


//斐波那契数列生成函数定义
int Fibonacci(int n)
{
	if (n == 0)
	{
		return 0;
	}
	else if (n == 1)
	{
		return 1;
	}
	else
	{
		int i = 0, j = 1,m=0;
		for (int k = 0; k < n-1; k++)
		{
			m = i + j;
			i = j;
			j = m;
		}
		return m;
	}
	return -1;
}