Algorithms Flashcards

1
Q

Binary search iterative

A
"sorted list
Complexity O(log2n)
Space complexity is o(1)
how many times we have to half n to to reach the target
''
def binary_search(lt, target):
    left_wall=-1
    right_w=len(lt)
    while left_wall guess:
            left_wall=mid
        else :
            return print (lt.index(guess))
    return False
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Binary search recursive

A
def binary_search_recursive(list1, element):
    if len(list1) == 0:
        return False
    else:
        mid = len(list1)//2
        if (element == list1[mid]):
            return True
        else:
            if element > list1[mid]:
                return binary_search_recursive(list1[mid+1:],element)
            else:
                return binary_search_recursive(list1[:mid],element)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Bubble sort

A

”””
Worst case scenario is O (n2)

”””

def bubble(list_a):
    indexing_length = len(list_a) - 1 
    sorted = False 
while not sorted:  
    sorted = True  

    for i in range(0, indexing_length): # For every value in the list
        if list_a[i] > list_a[i+1]: 
            sorted = False # These values are unsorted
            list_a[i], list_a[i+1] = list_a[i+1], list_a[i] 
return list_a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

quick sort

A
"""
average O(n log n)
space O (logn)

”””

def quick_sort(list):
    if len(list) <=1 :
        return list
    else:
        pivot=list.pop()
        list_greater=[]
        list_smaller=[]
        for item in list:
            if item
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

selection sort

A

”””
O (n2) time complexity - two loops
o (1) space
select a number , compare to all elem to the right. if we find a smaller value than we replace the min. once
the pass is concluded we move the min to the left most position an continue
“””

def selection(list):
    indexed=range(0,len(list)-1)
    for i in indexed:
        min=i
        for j in range(i+1,len(list)):
            if list[min] >list[j]:
                min=j
        if min != i:
            list[i],list[min]=list[min],list[i]
    return list
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

merge sort

A

’’’

TIme complexity O(nlogn) : n from merge , logn from cutting the window
Space complexity O(n)
‘’’

def merge_sort(list_to_sort):
    if len(list_to_sort) <=1:
        return list_to_sort
    mid=len(list_to_sort)//2
    left= merge_sort(list_to_sort[:mid])
    right= merge_sort( list_to_sort[mid:])
    print('left',left)
    print('right',right)
    left_pointer=right_pointer=0
    result=[]
    while  left_pointer
How well did you know this?
1
Not at all
2
3
4
5
Perfectly