UNIT III
UNIT III
Sorting is defined as an arrangement of data in a certain order. Sorting techniques are used to
arrange data (mostly numerical) in an ascending or descending order.
Telephone Directory: It is a book that contains telephone numbers and addresses of people in
alphabetical order.
Dictionary: It is a huge collection of words along with their meanings in alphabetical order.
Contact List: It is a list of contact numbers of people in alphabetical order on a mobile phone.
BUBBLE SORT
compares two elements and swaps them until they are in the intended order
def bubble_sort(list1):
for i in range(0,len(list1)-1):
for j in range(len(list1)-1):
if(list1[j]>list1[j+1]):
temp = list1[j]
list1[j] = list1[j+1]
list1[j+1] = temp
return list1
list1 = [5, 3, 8, 6, 7, 2]
OUTPUT
Example -
list1 = [5, 3, 8, 6, 7, 2]
First iteration
[5, 3, 8, 6, 7, 2]
It compares the first two elements and here 5>3 then swap with each other. Now we get new list
is -
[3, 5, 8, 6, 7, 2]
[3, 5, 8, 6, 7, 2]
[3, 5, 6, 8, 7, 2]
In fourth comparison, 8>7 then swap -
[3, 5, 6, 7, 8, 2]
[3, 5, 6, 7, 2, 8]
Here the first iteration is complete and we get the largest element at the end. Now we need to
the len(list1) - 1
Second Iteration
[3, 5, 6, 7, 2, 8] - > [3, 5, 6, 2, 7, 8] here 7>2 then swap their position. Now
Third Iteration
[3, 5, 2, 6, 7, 8] - > [3, 5, 2, 6, 7, 8] here 6<7 then no swap taken place. Now
Fourth Iteration -
Fifth Iteration