6 - Sorting
6 - Sorting
Sorting
A Sorting Algorithm is used to rearrange a given array or list
elements according to a comparison operator on the elements.
The comparison operator is used to decide the new order of
element in the respective data structure. Can sort in ascending
or descending pattern.
Bubble sort
Merge sort
Insertion sort
Selection sort
Heap Sort
2
Bubble Sort
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Example: Sort the following set of list below in ascending pattern.
5 1 4 2 8
5 1 4 2 8 1 4 5 2 8
1 5 4 2 8 1 4 2 5 8
3
Second pass: 1 step Third pass:
1 4 2 5 8 1 2 4 5 8 Therefore :
Three passes
3 Steps
1 4 2 5 8 1 2 4 5 8
1 2 4 5 8 1 2 4 5 8
1 2 4 5 8 1 2 4 5 8
4
Example: Sort the following set of list below in descending pattern.
5 1 4 2 8 3 6 9
5 4 2 8 1 3 6 9
5 1 4 2 8 3 6 9 5 4 2 8 3 6 1 9
5 4 1 2 8 3 6 9 5 4 2 8 3 6 9 1
5 4 2 1 8 3 6 9 5 4 2 8 3 6 9 1
5
Second pass: 4 steps
5 4 2 8 3 6 9 1
5 4 2 8 3 6 9 1 5 4 8 3 6 2 9 1
5 4 2 8 3 6 9 1 5 4 8 3 6 9 2 1
5 4 8 2 3 6 9 1 5 4 8 3 6 9 2 1
5 4 8 3 2 6 9 1
6
Third pass: 3 steps
5 4 8 3 6 9 2 1 5 8 4 6 3 9 2 1
5 4 8 3 6 9 2 1 5 8 4 6 9 3 2 1
5 8 4 3 6 9 2 1
5 8 4 6 9 3 2 1
5 8 4 3 6 9 2 1
5 8 4 6 9 3 2 1
7
Fourth pass: 3 steps
5 8 4 6 9 3 2 1 8 5 6 9 4 3 2 1
8 5 4 6 9 3 2 1 8 5 6 9 4 3 2 1
8 5 4 6 9 3 2 1 8 5 6 9 4 3 2 1
8 5 6 4 9 3 2 1
8 5 6 9 4 3 2 1
8
Fifth pass: 2 steps
8 5 6 9 4 3 2 1 8 6 9 5 4 3 2 1
8 5 6 9 4 3 2 1 8 6 9 5 4 3 2 1
8 6 5 9 4 3 2 1 8 6 9 5 4 3 2 1
8 6 9 5 4 3 2 1 8 6 9 5 4 3 2 1
9
Sixth pass: 1 step
8 6 9 5 4 3 2 1 8 9 6 5 4 3 2 1
8 6 9 5 4 3 2 1 8 9 6 5 4 3 2 1
8 9 6 5 4 3 2 1 8 9 6 5 4 3 2 1
8 9 6 5 4 3 2 1 8 9 6 5 4 3 2 1
10
Seventh pass: 1 step
8 9 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
11
Eighth pass:
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
9 8 6 5 4 3 2 1 9 8 6 5 4 3 2 1
Therefore :
Eight passes
20 Steps
12
Activity:
Sort the given below in ascending and descending
using Bubble Sort
23 2 8 14 25 11 12 0
8 15 0 33 13 1 42 5 39 56
13