Sorting 1
Sorting 1
Sorting
• Given a set (container) of n elements
• E.g. array, set of words, etc.
• Suppose there is an order relation that can be
set across the elements
• Goal Arrange the elements in ascending order
• Start 🡪 1 23 2 56 9 8 10 100
• End 🡪 1 2 8 9 10 23 56 100
Bubble Sort
• Simplest sorting algorithm
• Idea:
• 1. Set flag = false
• 2. Traverse the array and compare pairs of two
elements
• 1.1 If E1 ≤ E2 - OK
• 1.2 If E1 > E2 then Switch(E1, E2) and set flag = true
• 3. If flag = true goto 1.
• What happens?
Bubble Sort
1 1 23 2 56 9 8 10 100
2 1 2 23 56 9 8 10 100
3 1 2 23 9 56 8 10 100
4 1 2 23 9 8 56 10 100
5 1 2 23 9 8 10 56 100
---- finish the first traversal ---- Why Bubble Sort ?
---- start again ----
1 1 2 23 9 8 10 56 100
2 1 2 9 23 8 10 56 100
3 1 2 9 8 23 10 56 100
4 1 2 9 8 10 23 56 100
---- finish the second traversal ----
---- start again ----
………………….
Implement Bubble Sort
with an Array
void bubbleSort (Array S, length n) {
boolean isSorted = false;
int j=1;
while(!isSorted) {
isSorted = true;
• Selection Sort
• insert elements in a priority queue implemented with an
unsorted sequence
• remove them one by one to create the sorted sequence
• Insertion Sort
• insert elements in a priority queue implemented with a
sorted sequence
• remove them one by one to create the sorted sequence
Selection Sort
Divide step: l scans the sequence from the left, and r from the right.
A swap is performed when l is at an element larger than the pivot and r is at one
smaller than the pivot.
In Place Quick Sort (cont’d)