CS301 Lec44
CS301 Lec44
Lecture No.44
Data Structure
20 8 5 10 7
5 7 8 10 20
Elementary Sorting Algorithms
Selection Sort
Insertion Sort
Bubble Sort
Selection Sort
Main idea:
• find the smallest element
• put it in the first position
• find the next smallest element
• put it in the second position
•…
And so on, until you get to the end of the list
Selection Sort -- Example
a: 19 5 7 12
00 11 22 33
a: 5 19 7 12
0 1 2 3
a: 5 7 19 12
0 1 2 3
a: 5 7 12 19
0 1 2 3
a: 5 7 12 19
0 1 2 3
Selection Sort: Code
tmp=arr[posmin];
arr[posmin]=arr[count];
arr[count]=tmp;
}
}
Selection Sort: Code
return posmin;
}
Swap Action (SelectionSorting)
20 8 5 10 7
5 8 20 10 7
5 7 20 10 8
5 7 8 10 20
5 7 8 10 20
Selection Sort Analysis
a: 19 12 5 7
0 1 2 3
a: 12 19 5 7
0 1 2 3
a: 5 12 19 7
0 1 2 3
a: 5 7 12 19
0 1 2 3
Insertion Sort: Code
arr[pos+1] = val;
}
}
Insertion Sort -- animation
a: 19
12 19 5 7
0 1 2 3
a: 12 19 5 7
0 1 2 3
Insertion Sort -- animation (cont)
• second element 2 +
• …
• penultimate element N-1 +
• last element N
• Total (2+N)(N-1)/2 = O(N2)
Bubble Sort
a: 19 5 12 7 a: 5 12 7 19
0 1 2 3 0 1 2 3
a: 5 19 12 7 a: 5 7 12 19
0 1 2 3 0 1 2 3
a: 5 12 19 7 a: 5 7 12 19
0 1 2 3 0 1 2 3
a: 5 12 7 19 a: 5 7 12 19
0 1 2 3 0 1 2 3
a: 5 12 7 19 a: 5 7 12 19
0 1 2 3
Bubble Sort: Code
10 12 8 4 2 11 7 5
Divide and Conquer
10
4 12
8 10
8 12
4 2 11
5 7 11
5
Divide and Conquer
4
2 8
4 10
5 12
7 2
8 10
5 11
7 11
12