1

利用二分法删除数组中元素

二分法的思想主要是要设定起始值和终点值,计算中值,和给定值进行比较,如果大于给定值,则将中值作为终点值,否则作为起始值,重新计算中值

#include<stdio.h>
int main(){

    int array[10] = {1,2,3,5,8,15,20,30,100,200};
    int first=0,end=9,middle=(first+end)/2,num,i;
    scanf("%d",&num);
    bool right=0;
    for (int i=0; i<10; i++){
    	if (array[i]==num){
    		right = 1;
    		break;
		}
	}
	if (right==0){
		printf("num is not in array, donot need delete!");
		return 0;
	}
    while(array[middle]!=num){
    	if(array[middle] > num){
    		end = middle;
		}else{
			first = middle;
		}
		middle = (first + end)/2;
    	
	}
	printf("middle=%d\n",middle);
	for (i = middle;i<9;i++){
		array[i] = array[i+1];
	}
	
	
	
	printf("new array:\n");
	for (i=0;i<9;i++){
		printf("%d\n",array[i]);
	}	
	
	return 0;
}
posted @ 2024-04-30 15:56  Bonne_chance  阅读(6)  评论(0编辑  收藏  举报
1