开发者

When I put 2 the search works, if it is any other number, it doesn't [closed]

开发者 https://www.devze.com 2022-12-07 19:12 出处:网络
Closed. This question needs to be more focused. It is not currently accepting answers. Want to improve this question? Update the question so it focuses on one problem only by editing this
Closed. This question needs to be more focused. It is not currently accepting answers.

Want to improve this question? Update the question so it focuses on one problem only by editing this post.

Closed 2 hours ago.

Improve this question
def SortandSearch(l, s):
    low = 0
    mid = 0
    high = len(l) - 1
    for i in range(len(l)):
        for j in range(i + 1, len(l)):
            if l[i] > l[j]:
                l[i], l[j] = l[j], l[i]
    
    while low <= high:
        mid = (low + (high - low)) // 2
        
        if l[mid] == s:
            return mid
            
        elif l[mid] > s:
            low = mid + 1
        
        else:
            high = mid - 1

    return -1    
l = [int (l) for l in input("Enter the elements: ").split()]
s = int(input("Searching for: "))
SortandSearch(l, s)
print("Sorted list:", *l, sep = " ")
fl = SortandSearch(l, s)

if fl != -1:
    print("Found at position " + str(fl + 1) + ".")
else:
    print("Not found.&qu开发者_如何转开发ot;)

this is when i put 2 (the only number that works)

Enter the elements: 4 1 3 2
Searching for: 2
Sorted list: 1 2 3 4
Found at position 2.

this is when i put 3 (or any number other than 2)

Enter the elements: 4 1 3 2
Searching for: 3
Sorted list: 1 2 3 4
Not found.


because the way you get mid's position is wrong, and the way to change low and high is also wrong.

while low <= high:
    mid = (low + (high - low)) // 2
    if l[mid] == s:
        return mid
            
    elif l[mid] > s:
        low = mid + 1
    else:
        high = mid - 1

should be

while low <= high:
    mid = low + (high - low) // 2
    if l[mid] == s:
        return mid
    elif l[mid] > s:
        high = mid - 1
    else:
        low = mid + 1 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号