Sorting Algorithms: Bubble, Insertion, Selection, Quick, Merge, Bucket, Radix, Heap
Sorting Algorithms: Bubble, Insertion, Selection, Quick, Merge, Bucket, Radix, Heap
Pass 1
0 1 2 3 4 5
42
77 77
42 35 12 101 5
Bubble Sort
Pass 1
0 1 2 3 4 5
42 35
77 77
35 12 101 5
Bubble Sort
Pass 1
0 1 2 3 4 5
42 35 12
77 77
12 101 5
Bubble Sort
Pass 1
0 1 2 3 4 5
42 35 12 77 101 5
No need to swap
Bubble Sort
Pass 1
0 1 2 3 4 5
42 35 12 77 5
101 101
5
Bubble Sort
0 1 2 3 4 5
42 35 12 77 5 101
6 10 24 36
12
10
Insertion Sort
6 10 24 36
12
11
Insertion Sort
6 10 24 3
6
12
12
Insertion Sort
13
Insertion Sort
P1 P2 P3 P4 P5 P6 P7
14
Algorithm
INSERTION SORT(A)
#A is the array with N elements to be sorted
Step 1: Repeat For J=1 to N-1 do
Set key=A[J]
Set I=J-1
Repeat While I>=0 AND A[I]>key do
Set A[I+1]=A[I]
Set I=I-1
Done
Set A[I+1]=key
Done
Step 2: PRINT A
Step 3: Exit 15
Insertion Sort
16
Selection Sort
• Selection sort works by selecting the minimum from
the given sequence and swapping it with the first
element in the list.
17
Selection Sort : Example
8 4 6 9 2 3 1
After P1 1 4 6 9 2 3 8
After P2 1 2 6 9 4 3 8
After P3 1 2 3 9 4 6 8
After P4 1 2 3 4 9 6 8
After P5 1 2 3 4 6 9 8
After P6 1 2 3 4 6 8 9
After P7 1 2 3 4 6 8 9
18
Algorithm
SELECTION SORT(A)
#A is the array with n element to be sorted
Step 1: Repeat For i=0 to N-1 do
Set min=i
Repeat For j=i+1 to N-1 do
If A[j]<A[min] then
set min=j
End If
Done
If (A[i]>A[min]) then
swap A[i] and A[min]
EndIf
Done
Step 3: PRINT A
Step 4: Exit 19
Given sequence of numbers: 6, 18, 4, 10, 3, 2, 14.
Find the sequence of numbers after Pass 4 if the sorting
(increasing order) used is:
•Bubble
•Insertion
•Selection
20
Merge Sort