SortingAlgorithms
SortingAlgorithms
23 78 45 8 32 56 Original List
8 78 45 23 32 56 After pass 1
8 23 45 78 32 56 After pass 2
After pass 3
8 23 32 78 45 56
8 23 32 45 78 56 After pass 4
After pass 5
8 23 32 45 56 78
Kisumu Polytechnic - Data 5
Structures and algorithms
Selection Sort (cont.)
template <class Item>
void selectionSort( Item a[], int n) {
for (int i = 0; i < n-1; i++) {
int min = i;
for (int j = i+1; j < n; j++)
if (a[j] < a[min]) min = j;
swap(a[i], a[min]);
}
}
23 78 45 8 32 56 Original List
23 78 45 8 32 56 After pass 1
23 45 78 8 32 56 After pass 2
After pass 3
8 23 45 78 32 56
8 23 32 45 78 56 After pass 4
After pass 5
8 23 32 45 56 78
Kisumu Polytechnic - Data 11
Structures and algorithms
Insertion Sort Algorithm
template <class Item>
void insertionSort(Item a[], int n)
{
for (int i = 1; i < n; i++)
{
Item tmp = a[i];
8 23 78 45 32 56 After pass 1
8 23 32 78 45 56 After pass 2
After pass 3
8 23 32 45 78 56
8 23 32 45 56 78 After pass 4
6 3 9 1 5 4 7 2
divide
6 3 9 1 5 4 7 2
divide divide
6 3 9 1 5 4 7 2
3 6 1 9 4 5 2 7
merge merge
1 3 6 9 merge
2 4 5 7
1 2 3 4 5 7 8 9
Kisumu Polytechnic - Data Structures and algorithms 24
Mergesort – Example2
m 1
= m*2 – 2i
m
i 0
= m*2m – 2m – 1
Using m = log n
= n * log2n – n – 1
O (n * log2n )
Kisumu Polytechnic - Data 30
Structures and algorithms
Mergesort – Analysis
• Mergesort is extremely efficient algorithm with respect
to time.
– Both worst case and average cases are O (n * log2n )
• Arranging the array elements around the pivot p generates two smaller sorting
problems.
– sort the left section of the array, and sort the right section of the array.
– when these two smaller sorting problems are solved recursively, our bigger
sorting problem is solved.
swaps outside of the for loop swaps inside of the for loop