




Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!





If they are out of order, swap them This puts the largest element at the very end The last element is now in the correct and final place
If they are out of order, swap them This puts the second largest element next to last The last two elements are now in their correct and final places
Continue as above until you have no unsorted elements on the left
2
Example of bubble sort 3
7 2 8 5 4
2 7 8 5 4
2 7 8 5 4
2 7 5 8 4
2 7 5 4 8
2 7 5 4 8
2 5 7 4 8
2 5 4 7 8
2 7 5 4 8
2 5 4 7 8
2 4 5 7 8
2 5 4 7 8
2 4 5 7 8
2 4 5 7 8
(done)
Code for bubble sort
4
Selection sort
Given an array of length n,
Search elements 0 through n-1 and select the smallest
Swap it with the element in location 0
Search elements 1 through n-1 and select the smallest
Swap it with the element in location 1
Search elements 2 through n-1 and select the smallest
Swap it with the element in location 2
Search elements 3 through n-1 and select the smallest
Swap it with the element in location 3
Continue in this fashion until there’s nothing left to search
7
Example and analysis of
selection sort
The outer loop executes n-1 times
The inner loop executes about n/2 times on average (from n to 2 times)
Work done in the inner loop is constant (swap two array elements)
Time required is roughly (n-1)*(n/2)
You should recognize this as O(n 2 )
8
7 2 8 5 4
2 7 8 5 4
2 4 8 5 7
2 4 5 8 7
2 4 5 7 8
Code for selection sort
9
Invariants for selection sort
For the inner loop:
for all i such that outer <= i <= inner, a[min] <= a[i]
For the outer (enclosing) loop:
for all i <= outer, if i < j then a[i] <= a[j]
10
Analysis of insertion sort
The inner loop looks at (and moves) half of these
This gives a second factor of n/
13
Summary
Bubble sort is very slow, and should probably never be used for anything
Selection sort is intermediate in speed
Insertion sort is usually faster than selection sort—in fact, for small arrays (say, 10 or 20 elements), insertion sort is faster than more complicated sorting algorithms
14
References 15
Wirth, N. (1986), Algorithms & Data Structures , Upper
Saddle River, NJ: Prentice-Hall
Goodrich, M.T.; Tamassia, R. (2002). " Bucket-Sort and Radix-
Sort ". Algorithm Design: Foundations, Analysis, and Internet
Examples. John Wiley & Sons.