Unit - I-3
Unit - I-3
Linear search
if (list1[i] == key):
return i
return -1
list1 = [1 ,3, 5, 4, 7, 9]
n = len(list1)
if(res == -1):
else:
Output :
5 b) Binary Search
low = 0
high = len(list1) - 1
mid = 0
if list1[mid] < n:
low = mid + 1
high = mid - 1
else:
return mid
return -1
# Initial list1
# Function call
result = binary_search(list1, n)
if result != -1:
else:
output:
The list of numbers [12, 24, 32, 39, 45, 50, 54]
The list of numbers [12, 24, 32, 39, 45, 50, 54]
a) Selection sort
def selection_sort(array):
length = len(array)
for i in range(length-1):
minIndex = i
if array[j]<array[minIndex]:
minIndex = j
return array
array = [21,6,9,33,3]
print ("The sorted array is: ", selection_sort(array))
output :
b) Insertion Sort
def insertion_sort(list1):
value = list1[i]
# Move elements of list1[0..i-1], that are greater than value, to one position ahead
j=i-1
list1[j + 1] = list1[j]
j -= 1
list1[j + 1] = value
return list1
output :
prime=0
def primenum(x):
if x>=2:
for y in range(2,x):
if not(x%y):
return False
else:
return False
return True
if primenum(i):
prime+=1
print(i,end="\t")
output 1 :
30
2 3 5 7 11 13 17 19 23 29
output 2 :
20
2 3 5 7 11 13 17 19