Professional Documents
Culture Documents
1
Sorting means . . .
Sorting rearranges the elements into either
ascending or descending order within the array
(we’ll use ascending order).
2
Sorting also means…
There are several sorting algorithms available like bubble sort, selection sort and insertion
sort.
Sorting operation is performed in many applications to provide the output in desired order.
For example listing all the product in the increasing order of their names or decreasing order
of supplier names
List containing exam scores sorted from lowest to highest or vice versa
We will study Bubble Sorting, Selection Sorting and Insertion Sorting in this lab course
5,3,8,6,7,2
If first value is greater than second value then
exchange.
If first value>second value, Swap,
If first value<second value, No swap
ITERATION 1
5,3,8,6,7,2--------3,5,8,6,7,2 (5>3)True
3,5,8,6,7,2--------3,5,8,6,7,2 (5>8)False
3,5,8,6,7,2--------3,5,6,8,7,2 (8>6)True
3,5,6,8,7,2--------3,5,6,7,8,2 (8>7)True
3,5,6,7,8,2--------3,5,6,7,2,8 (8>2)True
4
ITERATION 2
3,5,6,7,2,8 ------3,5,6,7,2,8
3,5,6,7,2,8-------3,5,6,7,2,8
3,5,6,7,2,8-------3,5,6,7,2,8
3,5,6,7,2,8-------3,5,6,2,7,8 (7>2) True
3,5,6,2,7,8-------3,5,6,2,7,8
…………. and so on
At the end of Iteration 5 all the elements
will be sorted in ascending order.
5
Swapping
a = 2, b =3
Introducing New Variable “t”
t<----a; t =2,
Now a will be empty
a<----b; a=3,
Now b will be empty
b<-----t; b=2,
Finally a=3 and b=2
6
Solved Program
Write a python Program to sort the numbers in the list in
ascending order using Bubble Sort. List = [5,3,8,6,7,2]
Selection Sort
8
(5,3,8,6,7,2)
(5,3,8,6,7,2)
Minimum Value = 5 and Compare.
Minimum Value = 3 and Compare.
Minimum Value = 2
Finally Minimum Value is 2, then swap (5,2)
(2,3,8,6,7,5)
Now 2 is fixed and no need to sort.
(2,3,8,6,7,5)
Minimum Value = 3 and Compare.
Finally Minimum Value is 3 and no need to swap
(2,3,8,6,7,5)
Now 2 and 3 is fixed and no need to sort.
(2,3,8,6,7,5)
and so on…………………
At the end of so all iterations we get sorted all the numbers as
9
(2,3,5,6,7,8)
Solved Program
Write a python Program to sort the numbers in the list in
ascending order using Selection Sort. List = [5,3,8,6,7,2]
10
Insertion Sort in Real Life
11
Solved Program
Write a python Program to sort the numbers in the list in ascending
order using Insertion Sort. List = [14,46,43,27,57,41,45,21,70]
12