-1

I have an assingment. the assingment says to write two functions in python that will:

  1. Sort the the list using bubble Sort
  2. Take numerical input from the user and search the previously sorted list for that number.

My first function - sort - can sort. However, my second function is not performing a binary search correctly. My end goal is to combine the two functions.

Here is my current code:

Bubble Sort

def sort(x):
        for j in range(len(x)):
            for i in range (len(x)-1):
                if x[i]> x[i+1]:
                    temp =x[i]
                    x[i]=x[i+1]
                    x[i+1]=temp
        return x

    sl = sort([87,56,34,23,89,15,2,200,28,31])
    print (sl)         

Binary Search

def bs(t):

    s = 0 
    e = len(t)-1
    found = False
    c = int(input("Enter"))
    while (s<=e):
        mid = (s+e)//2
        if t[mid]==c:
            found = True
        elif c > t[mid]:
            s = mid+1
        else:
            e = mid-1
    return found
bs([1,2,3,4,5])
Christian Dean
  • 22,138
  • 7
  • 54
  • 87
SSH
  • 43
  • 1
  • 12
  • 1
    I don't understand your question. What is wrong with the code you've shown? Are you getting error messages? Wrong output? You need to show what's going wrong or we can't help you fix it. – Blckknght Sep 12 '17 at 21:09
  • In case of binary search it's not returning any result. Secondly how to use sorted list that generated in 1st function in my search function – SSH Sep 12 '17 at 21:17

1 Answers1

1

The problem is in your while loop. In case item is found s or e not increment/decrement and loop becomes infinite.

You should add break statement or split if conditions:

def bs(t):
    t = sort(t)

    s = 0 
    e = len(t)-1
    found = False
    c = int(input("Enter"))
    while (s<=e):
        mid = (s+e)//2
        if t[mid]==c:
            found = True
            break
        elif c > t[mid]:
            s = mid+1
        else:
            e = mid-1
    return found
bs([1,2,3,4,5])

or:

def bs(t):
    t = sort(t)

    s = 0 
    e = len(t)-1
    found = False
    c = int(input("Enter"))
    while (s<=e):
        mid = (s+e)//2
        if t[mid]==c:
            found = True

        if c > t[mid]:
            s = mid+1
        else:
            e = mid-1
    return found
bs([1,2,3,4,5])

combined function ( sort + bs ):

def binary_search(x):
for j in range(len(x)):
    for i in range(len(x) - 1):
        if x[i] > x[i + 1]:
            temp = x[i]
            x[i] = x[i + 1]
            x[i + 1] = temp

    s = 0
    e = len(x)-1
    found = False
    c = int(input("Enter"))

    while s <= e:
        mid = (s + e)//2
        if x[mid] == c:
            found = True
            break
        elif c > x[mid]:
            s = mid+1
        else:
            e = mid-1

    return found

combined with some refactoring:

def binary_search(x):
    # j is not used, so it could be replaced with underscore
    for _ in range(len(x)):
        for i in range(len(x)-1):
            if x[i] > x[i+1]:
                # this is illustration of python awesomeness
                x[i], x[i+1] = x[i+1], x[i]

    c = int(input("Enter"))

    while x:
        # this line is actually the same as s + e, because 
        # is always equals to list's len - 1
        mid = (len(x)-1)//2

        # instead of redefining variable - just break from loop
        if x[mid] == c:
            break

        if c > x[mid]:
            # slice list instead of computing new start index
            x = x[mid+1:]
        else:
            # slice list instead of computing new last index
            x = x[:mid-1]

    return len(x) > 0  # true if x contains at least one el and false otherwise 


sl = binary_search([87, 56, 34, 23, 89, 15, 2, 200, 28, 31])
print(sl)
Yaroslav Surzhikov
  • 1,568
  • 1
  • 11
  • 16
  • i replaced while with #for i in range(len(t))# it was working now that you mentioned i got the logic and i think using while and break or for and break will be the efficient way.. else in for it will keep rotating thanks man. would it possible to help me out on the other part of the problem i.e now how can use the sorted list form 1st function and use the values in current function to run it . like it will sort and then take value and then display available or not . – SSH Sep 12 '17 at 21:49
  • Replacing `while` with `for` actualy increases algorithm time to exec and it's not a binary search. If you want it to be a binary search - use `while`. About sorting: sure, why not ? Just add something like `t = sort(t)` right after `def bs(t):`. – Yaroslav Surzhikov Sep 12 '17 at 21:58
  • its not working probably am doing it somewhere wrong – SSH Sep 12 '17 at 22:40
  • @SubhaSaha i've edited the answer – Yaroslav Surzhikov Sep 12 '17 at 22:42
  • i mean the sorting part – SSH Sep 12 '17 at 22:43
  • @SubhaSaha added combined function to the answer + my variant with explanation – Yaroslav Surzhikov Sep 12 '17 at 23:04
  • @yarolsavsurzhikov all i have to say def thanks() – SSH Sep 12 '17 at 23:06
  • Just one more question //x[i], x[i+1] = x[i+1], x[i]// is it doing the same thing that a temp variable was doing – SSH Sep 12 '17 at 23:18
  • @SubhaSaha yes. You can read detailed answer why at this link: https://stackoverflow.com/a/14836456/8489834 – Yaroslav Surzhikov Sep 12 '17 at 23:21