0% found this document useful (0 votes)
3 views2 pages

Sorting

The document contains Python implementations of three sorting algorithms: bubble sort, selection sort, and a binary search function. It includes user input for sorting a list of numbers and outputs the sorted list. The binary search function also tracks the number of iterations taken to find a target value in a predefined list.

Uploaded by

satya narendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Sorting

The document contains Python implementations of three sorting algorithms: bubble sort, selection sort, and a binary search function. It includes user input for sorting a list of numbers and outputs the sorted list. The binary search function also tracks the number of iterations taken to find a target value in a predefined list.

Uploaded by

satya narendra
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

BINARY SEARCH BUBBLE SORT QUICK SORT

def binarySearch(target, List):

left = 0
right = len(List) - 1
global iterations
iterations = 0
while left <= right:
# The following line was not indented correctly
iterations += 1
mid = (left + right) // 2
if target == List[mid]:
return mid
elif target < List[mid]:
right = mid - 1
else:
left = mid + 1
return -1
if __name__ == '__main__':
List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14]
target = 12
answer = binarySearch(target, List)
if(answer != -1):
print('Target',target,'found at position', answer, 'in',
iterations,'iterations')
else:
print('Target not found')

def bubble_sort(alist):
for i in range(len(alist) - 1, 0, -1):
no_swap = True
for j in range(0, i):
if alist[j + 1] < alist[j]:
alist[j], alist[j + 1] = alist[j + 1], alist[j]
no_swap = False
if no_swap:
return

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
bubble_sort(alist)
print('Sorted list: ', alist)
BINARY SEARCH BUBBLE SORT QUICK SORT

def selection_sort(alist):
for i in range(0, len(alist) - 1):
smallest = i
for j in range(i + 1, len(alist)):
if alist[j] < alist[smallest]:
smallest = j
alist[i], alist[smallest] = alist[smallest], alist[i]

alist = input('Enter the list of numbers: ').split()


alist = [int(x) for x in alist]
selection_sort(alist)
print('Sorted list: ', alist)

You might also like