找到的最小数目大于一个给定数量中排序列表 [英] Find the smallest number that is greater than a given number in a sorted list

查看:134
本文介绍了找到的最小数目大于一个给定数量中排序列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于数字的排序列表,我需要找到的最小数目大于给定数。考虑一下这个列表:

Given a sorted list of numbers, I need to find the smallest number that is greater than a given number. Consider this list:

arr=[1,2,3,5,7,11,101,131,151,181,191,313,353,373,383]

说出指定的号码是320。然后,我的方法应该返回353为353比320的最小数量越多。

Say the specified number is 320. Then, my method should return 353 as 353 is the smallest number greater than 320.

我想使用二进制搜索稍加修改的形式;然而在执行程序进入无限循环。

I am trying to use a slightly modified form of binary search; however on execution the program goes into infinite loop.

def modBinarySearch(arr,x):
    l=len(arr)
    mid=l/2
    if arr[mid]>=x and arr[mid-1]<x:
        return arr[mid]
    elif arr[mid]>x and arr[mid-1]>x:
        modBinarySearch(arr[mid:l],x)
    else: 
        modBinarySearch(arr[0:mid],x)

N=int(raw_input())
arr=[1,2,3,5,7,11,101,131,151,181,191,313,353,373,383]
print modBinarySearch(arr,N)

有人能指出我在做什么错了?

Can someone point out what I am doing wrong ?

推荐答案

如果ARR [MID]和ARR [中期1],两者都大于你的号码,你应该在ARR搜索[0:MID],不要你不觉得?

If arr[mid] and arr[mid-1], both are greater than your number, you should search in arr[0:mid], don't you think?

 elif arr[mid]>x and arr[mid-1]>x:
    modBinarySearch(arr[0:mid],x)
else: 
    modBinarySearch(arr[mid:1],x)

这篇关于找到的最小数目大于一个给定数量中排序列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆