在排好序的数组中使用两种不同的方法获取目标数字的索引(第三次作业)

在排好序的数组中使用两种不同的方法获取目标数字的索引
问题:
在排序好的数组中使用两种不同的方法获取目标数字的索引,如果不存在返回0。
解析:
在一个数组里面查找一个数字的方法最直接的就是使用暴力的方法进行搜索,遍历每一个数组查询到目标数字即可返回。因为这个数组是排好序的,所以我们便可以使用二分搜索的方法来查找这个数字。(便于操作我们令得到的数组是升序排序的)
设计:

1)暴力算法:	
For(数组){
	If(arr[i] == x){
		return i;
		退出
	}
}
Return 0;2)二分查找算法:
L = 1
R = n
While(R >= L){
	Mid = (R + L) / 2;
	If(arr[Mid] == x)return Mid;
	Else if(查到的数大于目标数){
		收缩右区间
	}
	Else if(查到的数小于目标数){
		增加左区间
	}
}

分析:
(1)暴力算法:O(n)
(2)二分查找算法:O(log n)

代码:

#include<iostream>
#include<algorithm>
#include<stdlib.h>
using namespace std;

const int maxn = 1e3 + 10;

int n, m, arr[maxn];

int Violence_search(int x){
    int index = 0;
    for(int i = 1; i <= n; i++){
        if(arr[i] == x){
            index = i;
            break;
        }
    }
    return index;
}

int Binary_search(int x){
    int l = 1;
    int r = n;
    while(r >= l){
        int mid = (l + r) >> 1;
        if(arr[mid] == x){
            return mid;
        }else if(arr[mid] > x){
            r = mid - 1;
        }else{
            l = mid + 1;
        }
    }
    return 0;
}


int main(){
    scanf("%d %d", &n, &m);
    for(int i = 1; i <= n; i++)scanf("%d", &arr[i]);
    int p1, p2;
    p1 = Violence_search(m);
    p2 = Binary_search(m);
    printf("Using violence method to get index : %d\n", p1);
    printf("Using binary method to get index : %d\n", p2);
    system("pause");
    return 0;
}
/*
5 3
7 8 9 10 11
10 5
1 4 5 6 7 8 9 11 12 13
*/

github源码地址:
传送门

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值