1. 程式人生 > >沒有遞迴的二分查詢

沒有遞迴的二分查詢

開銷較小

#include <stdio.h>
#include <time.h>


#define SIZE 20


void print_array(int a[], int len)
{
	int i = 0;
	for (i = 0; i < len; i++){
		printf("%d,", a[i]);
	}
	printf("\n");
}
void swap(int a[], int i, int j)
{
	int temp = a[i];
	a[i] = a[j];
	a[j] = temp;
}

void selection_sort(int a[],int len)
{
	int i = 0;
	int j = 0;
	for (i = 0; i < len; i++){
		for (j = i; j < len;j++){
			if (a[j] < a[i]){
				swap(a,i,j);
			}
		}
	}
}


int binary_search_ex(int a[], int low, int high, int key)
{
	int ret = -1;

	while (low <= high){
		int mid = (low + high) / 2;
		if (a[mid] == key){
			ret = mid;
			break;
		}
		else if (a[mid] > key){
			high = mid - 1;
		}
		else{
			low = mid + 1;
		}
		printf("%d\n",mid);
	}

	return ret;
}


int main(void){
	int a[SIZE] = { 0 };
	int i = 0;
	int key = 0;
	int index = -1;

	srand((unsigned int)time(NULL));

	for (i = 0; i < SIZE; i++){
		a[i] = rand() % 100;
	}

	key = rand() & 100;

	printf("Static Search Demo\n");
	printf("Key: %d\n", key);
	printf("Array: \n");
	print_array(a, SIZE);
	selection_sort(a,SIZE);
	print_array(a, SIZE);
	index = binary_search_ex(a, 0,SIZE, key);
	if (index >= 0){
		printf("SUCCED: a[%d] = %d\n", index, a[index]);
	}
	else{
		printf("Failed!!\n");
	}

	system("PAUSE");
	return 0;
}