lundi 23 août 2021

Can anyone help me with the following code? I want to understand what the code do?

I am a beginner in programming and I am trying to understand a code that sorts random numbers and how binary search work.

import random
def bub_sort(a):
    for i in range(len(a)-1):
        for j in range(len(a)-1-i):
            if a[j]>a[j+1]:
                a[j],a[j+1]=a[j+1],a[j]
    return a
    


def ins_sort(a):
    for i in range(1,len(a)):
        for j in range(0,i):
            if a[j]>a[i]:
                a[j],a[i]=a[i],a[j]
    return a



def bin_search(L,s):
    low=0
    high=len(L)-1
    while low<=high:
        m=(low+high)//2
        if L[m]==s:
            return 1,m
        elif L[m]>s:
            h=m-1
        else:
            L=m+1
    return 0,None
            
  

L=[]
for i in range(10):
    n=random.randint(1,100)
    L.append(n)
s=int(input("Enter search element"))
l1=bub_sort(L)
ans=bin_search(l1,s)
if ans[0]==1:
    print("found at index ",ans[1])
else:
    print("not found")

Can anyone help me understand the whole code? I am very sorry for posting such a simple question.




Aucun commentaire:

Enregistrer un commentaire