Professional Documents
Culture Documents
Lecture 02 Daa
Lecture 02 Daa
Lecture 02 Daa
SELECTION SORT
&
BUBBLE SORT
LECTURE - 02
Dr. Ragini Karwayun
SELECTION SORT
• Idea:
ØFind the smallest element in the array
Øexchange it with the element in the first position
Øfind the second smallest element and exchange it with the element in the second
position
Øcontinue until the array is sorted
• Disadvantage:
Ørunning time depends only slightly on the amount of order in the file
1
9/24/22
EXAMPLE
j i n j i
8 4 3 5 2 7 6
i n 1 7
j
2 4 3 5 8 7 6 2 6
j i n
2 3 4 5 8 7 6 3 5
j i n
2 3 4 5 8 7 6 4 4
j i n
2 3 4 5 6 7 8 5 3
j i n
6 2
2 3 4 5 6 7 8
2 3 4 5 6 7 8
2 3 4 5 6 7 8
Done
SELECTION SORT
ALGORITHM : SELECTION-SORT(A)
1. n ← length[a]
2. for j ← 1 to n - 1
3. Smallest ← j
4. for i ← j + 1 to n
5. If a[i] < a[smallest]
6. then smallest ← i
7. Exchange a[j] ↔ a[smallest]
2
9/24/22
SELECTION SORT
SELECTION-SORT(A) cost times
1. n ← length[a] C1 1
2. for j ← 1 to n – 1 C2 n
3. smallest ← j C3 n-1
4. for i ← j + 1 to n C4 ∑$%#
!"# 𝑛 − 𝑗 + 1
SELECTION SORT
3
9/24/22
BUBBLE SORT
• Idea:
–repeatedly pass through the array
–swaps adjacent elements that are out of order
i n
1 2 3 4 5 6 7
j
• Easier to implement, but slower than insertion sort
EXAMPLE
j i j i j
i
8 4 3 5 2 7 6 2 8 4 3 5 6 7 2 3 8 4 5 6 7
8 4 3 5 2 6 7 2 8 4 3 5 6 7 2 3 8 4 5 6 7
8 4 3 5 2 6 7 2 8 4 3 5 6 7 2 3 8 4 5 6 7
8 4 3 2 5 6 7 2 8 4 3 5 6 7 2 3 8 4 5 6 7
8 4 2 3 5 6 7 2 8 3 4 5 6 7 2 3 4 8 5 6 7j i
8 2 4 3 5 6 7 1 7
2 3 8 4 5 6 7
2 6
2 8 4 3 5 6 7
3 5
Done
4 4
IPEC KCS-503. Design and Analysis of Algorithms Dr. Ragini Karwayun
5 3
8 6 2
4
9/24/22
EXAMPLE
j i j i j
i
2 3 4 8 5 6 7 2 3 4 5 8 6 7 2 3 4 5 6 8 7
2 3 4 8 5 6 7 2 3 4 5 8 6 7 2 3 4 5 6 7 8
2 3 4 8 5 6 7 2 3 4 5 6 8 7 Done i j
1 7
2 3 4 5 8 6 7
2 6
3 5
4 4
5 3
6 2
7 1
IPEC KCS-503. Design and Analysis of Algorithms Dr. Ragini Karwayun
BUBBLE SORT
• ALGORITHM : BUBBLE-SORT(A)
• for i ← 1 to length[A]
• do for j ← length[A] down to i + 1
• do if A[j] < A[j -1]
• then exchange A[j] ↔ A[j-1]
10
5
9/24/22
T(n) = Θ(n2)
11