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


    #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("
    ");
    }
    int main() {
    	int i, n = 10;
    	int list[MAX_SIZE];
    
    	for(i = 0; i < n; i++) {
    		list[i] = rand() % 1000;
    		printf("%d
    ", list[i]);
    	}
    
    	printf("*******************
    ");
    
    	sort(list, n);
    	for(i = 0; i < n; i++) {
    		printf("%d
    ", list[i]);
    	}
    
    	int result = binsearch(list, list[2], 0, n);
    	printf("result = %d
    ", result);
    	printf("*******************
    ");
    
    	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);
    	}
    }
    

      

  • 相关阅读:
    如何过滤php中危险的HTML代码
    一个老总的语录
    php如何优化压缩的图片
    php时间函数time(),date(),mktime()区别
    php中获取网站访客来源的关键词方法
    php获取QQ头像并显示的方法
    php一些常规动态设置与获取
    xss过滤函数
    php获取当月的第一天以及最后一天
    php eval函数一句话木马代码
  • 原文地址:https://www.cnblogs.com/maduar/p/13211392.html
Copyright © 2020-2023  润新知