2016-06-16 10 views
0

以下はpython3バージョンで書かれたバイナリ検索の完全なコードです。 私は以下を行うことができました:-i)リストを作成する、ii)バブルソートアルゴリズムを使用してリストをソートする、iii)バイナリ検索を使用して番号を検索するコードスニペットを作成する しかし、存在する/存在しないリスト内で)、私のコードは無限ループに入り、何も結果を与えません。 エラーを探してみましたが、コードをデバッグできませんでした。Pythonでバイナリ検索アルゴリズム(関数を実装しないで)を検索する方法

また、リスト内の数字のインデックスを取得するにはどうすればよいですか?私はlist.index()メソッドを使うことを考えました。ソートされたリストの場合や、インデックス番号の出力が間違って表示されることはありますか?

list=[] 
item=0 
while item!="99": 
    item=input("Enter the number, To discontinue enter 99:") 

    if item.isdigit(): #isdigit() checks whether input string consists of digits only 
     list.append(int(item)) #convert the input string into number 
    else: 
     list.append(item) 

del list[-1] #Delete the number at last index of the list. It will delete "99", 
      #which we have used to discontinue the loop 

print("The unsorted list is: ",list) 

#Using bubble sort algorithm to sort the list 
length=len(list) 

for i in range(length): 
    for j in range(length-1): 
     if list[j]>list[j+1]: 
      list[j],list[j+1]=list[j+1],list[j] 

print("Our sorted list is: ",list) 

#Implementing binary serach algorithm 

target=int(input("Enter the number you are looking for: ")) 
first=0    #First index of list is 0 
last=len(list)-1  #Last index of list is "length of list minus 1" 
mid=(first+last)//2 

while first<=last: 
    if list[mid]<target:  #If element at middle index is less than the target element,shift new lower index to one more than middle index 
     low=mid+1      
    elif list[mid]==target:  #else, if element at middle index is same as target element 
     print("Number is found at index") 
     break 
    else: 
     last=mid-1 
    mid=(first+last)//2 
    if (first>last): 
     print("Number not found in list") 
+1

任意の機能を実装しないための動機は何であるの数字のインデックスであることに注意してください?それは悪いコードにつながることがほぼ保証されている任意の制限のようです。 –

+0

文脈から、私はこれが宿題であると確信しています。そして実際には*彼は[標準的なpython関数](https://docs.python.org/3/library/bisect.html)を使うべきではありません。 、そのビットは誤解されてしまった。 – spectras

+1

コードで 'first'と' low'を使うことがあります。おそらくバグの起源。それを選択し、他の名前を変更します。 – spectras

答えて

1

無限ループがライン

low=mid+1 

からである私が何を意味する

last=mid+1 

エラーがケースlist[mid]<targetが起こるだろうが、low以降に変更されていることであったと思いますlastmid変更されない場合は、次の反復で再びケースがトリガーされます。

EDIT:またmidリスト

+0

あなたは絶対に正しいです。そのキャッチをありがとう。おそらく、私は非常に多くの用語(最初、最後、中期)と複雑なアルゴリズムで台無しになって、そのミスを... –

関連する問題