Beruflich Dokumente
Kultur Dokumente
Rada Mihalcea
http://www.cs.unt.edu/~rada/CSCE3110
Sorting (I)
Reading: Chap.7, Weiss
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 ----
---- start again ---- Why Bubble Sort ?
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;
while(!isSorted) {
isSorted = true;
for(i = 0; i<n; i++) {
if(S[i] > S[i+1]) {
int aux = S[i];
S[i] = S[i+1]; S[i+1] = aux; isSorted = false;
}
}
}
Running Time for Bubble Sort
One traversal = move the maximum element
at the end
Traversal #i : n – i + 1 operations
Running time:
(n – 1) + (n – 2) + … + 1 = (n – 1) n / 2 = O(n
2)
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)