0% found this document useful (0 votes)
165 views4 pages

Assignment - Bubble Sort and Insertion Sort Implementation

Download as docx, pdf, or txt
0% found this document useful (0 votes)
165 views4 pages

Assignment - Bubble Sort and Insertion Sort Implementation

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 4

1. Write program code for the most efficient bubble sort algorithm.

Assume
that the items to be sorted are stored in a 1D array with n elements.

def bubble(list_a):

indexing_length = len(list_a) - 1

sorted = False

while not sorted:

sorted = True

for i in range(0, indexing_length):

if list_a[i] > list_a[i+1]:

sorted = False

list_a[i], list_a[i+1] = list_a[i+1], list_a[i]

return list_a

print(bubble([4,8,1,16,8,2,9,33,7,6,69]))

2. Dry-run the insertion sort algorithm using a trace table. Assume the list consists
of the following six items in the order given: 53, 21, 60, 18, 42, 19.

Trace Table for [53, 21, 60, 18, 42, 19]

Hole Position ValueTo Insert A(holePosition- A


1)>ValueToInsert
1 21 True [21,53,60,18,
42,19]

2 60 False [21,53,60,18,
42,19]

3 18 True [21,53,18,60,
42,19]

2 18 True [21,18,53,60,
42,19]

1 18 True [18,21,53,60,
42,19]

4 42 True [18,21,53,42,
60,19]

3 42 True [18,21,42,53,
60,19]

2 42 False [18,21,42,53,
60,19]

5 19 True [18,21,42,53,
19,60]

4 19 True [18,21,42,19,
53,60]

3 19 True [18,21,19,42,
53,60]

2 19 True [18,19,21,42,
53,60]

1 19 False [18,19,21,42,
53,60]
3. Write program code for the insertion sort algorithm. Assume that the items to be
sorted are stored in a 1D array with n elements.

def insertion_sort(list_a):

indexing_length = range(1, len(list_a))

for i in indexing_length:

value_to_sort = list_a[i]

while list_a[i-1] > value_to_sort and i>0:

list_a[i], list_a[i-1] = list_a[i-1], list_a[i]

i = i -1

return list_a

print(insertion_sort([10, 9, 8, 7, 6, 5, 4, 3, 2, 1]))

4. Write a program to get character inputs from the user and output the sorted
character list.

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

c = int(input("Enter the third number: "))


d = int(input("Enter the fourth number: "))

e = int(input("Enter the fifth number: "))

f = int(input("Enter the sixth number: "))

array = [a, b, c, d, e, f]

aa = int(array.count(a))

bb = int(array.count(b))

cc = int(array.count(c))

dd = int(array.count(d))

ee = int(array.count(e))

ff = int(array.count(f))

for i in array:

if i > 100 or i < 1 or aa and bb and cc and dd and ee and ff > 1:

print("Number should be smaller than 100 and larger than 1


and numbers can't be repeated")

else:

array.sort()

print(array)

You might also like