• 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);
    	}
    }
    

      

  • 相关阅读:
    JVM-对象的创建
    maven依赖无法下载依赖包,PKIX认证不通过
    Object里面的方法
    Java多线程之volatile与synchronized比较
    java 二叉树的创建 遍历
    设计模式之单例模式
    博客园自定义主题 皮肤
    mysql索引 b+树
    sleep和wait的区别(转)
    final/finally/finalize的区别(转)
  • 原文地址:https://www.cnblogs.com/maduar/p/13211392.html
Copyright © 2020-2023  润新知