#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 20
//打印数组
void println(int array[], int len)
{
int i = 0;
for(i=0; i<len; i++)
{
printf("%d ", array[i]);
}
printf("
");
}
//交换数据
void swap(int array[], int i, int j)
{
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//选择排序
void SelectionSort(int array[], int len) // O(n*n)
{
int i = 0;
int j = 0;
int k = -1;
for(i=0; i<len; i++)
{
k = i;
for(j=i; j<len; j++)
{
if( array[j] < array[k] )
{
k = j;
}
}
swap(array, i, k);
}
}
//二分查找--思想 大 《--》小 递归查找
int binary_search(int a[], int low, int high, int key) // O(logn)
{
int ret = -1;
if( low <= high )
{
int mid = (low + high) / 2;
if( a[mid] == key )
{
ret = mid;
}
// low ---> mid - 1
else if( key < a[mid] )
{
ret = binary_search(a, low, mid-1, key);
}
// mid --> high
else if( key > a[mid] )
{
ret = binary_search(a, mid+1, high, key);
}
}
return ret;
}
// 二分查找 应用非递归 效率大大提高。
int binary_search_ex(int a[], int low, int high, int key) // O(logn)
{
int ret = -1;
while( low <= high )
{
int mid = (low + high) / 2;
if( a[mid] == key )
{
ret = mid;
break;
}
else if( key < a[mid] )
{
high = mid - 1;
}
else if( key > a[mid] )
{
low = mid + 1;
}
}
return ret;
}
// 插值查找算法 《概论》
int interpolation_search(int a[], int low, int high, int key)
{
int ret = -1;
while( (low <= high) && (a[low] <= key) && (key <= a[high]) )
{
// 0 < fx < x 转换成float
float fx = 1.0f * (key - a[low]) / (a[high] - a[low]);
int mid = low + fx * (high - low);
if( a[mid] == key )
{
ret = mid;
break;
}
else if( key < a[mid] )
{
high = mid - 1;
}
else if( key > a[mid] )
{
low = mid + 1;
}
}
return ret;
}
int main(int argc, char *argv[])
{
int a[SIZE] = {0};
int i = 0;
int key = 0;
int index = 0;
//获取时间
srand((unsigned int)time(NULL));
//获取随机数组
for(i=1; i<=SIZE; i++)
{
a[i] = rand() % 100;
}
key = 50;
printf("Binary Search Demo
");
printf("Key: %d
", key);
printf("Array:
");
//选择排序
SelectionSort(a, SIZE);
打印
println(a, SIZE);
index = interpolation_search(a, 0, SIZE-1, key);
if( index > 0 )
{
printf("Success: a[%d] = %d
", index, a[index]);
}
else
{
printf("Failed!
");
}
return 0;
}