码迷,mamicode.com
首页 > 编程语言 > 详细

C语言数据结构-折半查找

时间:2020-06-30 09:12:57      阅读:83      评论:0      收藏:0      [点我收藏+]

标签:ddl   c语言   print   res   def   数据   bin   and   i++   

#include<stdio.h>
#include<stdlib.h>

#define MAX_SIZE 101
#define SWAP(x, y, t)((t) = (x), (x) = (y), (y) = t)
#define COMPARE(x, y)((x) < (y)) ? -1 : ((x) == (y)) ? 0 : 1;

void sort(int [], int);
int binsearch(int list[], int searchnum, int left, int right) {
	int middle;
	int key;
	if(left <= right) {
		middle = (left + right) /2;
		key = COMPARE(list[middle], searchnum);
		if(key == -1) {
			return binsearch(list, searchnum, middle + 1, right);
		} else if(key == 0) {
			return middle;
		} else if(key == 1) {
			return binsearch(list, searchnum, left, middle -1);
		}
	}
	return -1;
}

void perm(char *list, int i, int n) {
	int j, temp;
	if(i == n) {
		for(j = 0; j <= n; j++) {
			printf("%c", list[j]);
		}
		printf("   ");
	} else {
		for(j = i; j <=  n; j++) {
			SWAP(list[i], list[j], temp);
			perm(list, i + 1, n);
			SWAP(list[i], list[j], temp);
		}
	}
	printf("\n");
}
int main() {
	int i, n = 10;
	int list[MAX_SIZE];

	for(i = 0; i < n; i++) {
		list[i] = rand() % 1000;
		printf("%d\n", list[i]);
	}

	printf("*******************\n");

	sort(list, n);
	for(i = 0; i < n; i++) {
		printf("%d\n", list[i]);
	}

	int result = binsearch(list, list[2], 0, n);
	printf("result = %d\n", result);
	printf("*******************\n");

	char a[] = {‘a‘, ‘b‘, ‘c‘};
	perm(a, 0, 2);
	return 1;
}

void sort(int list[], int n){
	int i, j, min, temp;
	for(i = 0; i < n -1; i++) {
		min = i;
		for(j = i + 1; j < n; j++) {
			if(list[j] < list[min]) {
				min = j;
			}
		}
		SWAP(list[i], list[min], temp);
	}
}

  

C语言数据结构-折半查找

标签:ddl   c语言   print   res   def   数据   bin   and   i++   

原文地址:https://www.cnblogs.com/maduar/p/13211392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!