Menu Driven Program in C
Menu Driven Program in C
• The first three are the foundations for faster and more
efficient algorithms.
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
Copy Right: Staffordshire University
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]);
}
}
template < class Object>
void swap( Object &lhs, Object &rhs )
{
Object tmp = lhs;
lhs = rhs;
rhs = tmp;
}
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
Copy Right: Staffordshire University
Insertion Sort Algorithm
template <class Item>
void insertionSort(Item a[], int n)
{
for (int i = 1; i < n; i++)
{
Item tmp = a[i];
After pass 1
8 23 78 45 32 56
After pass 2
8 23 32 78 45 56
After pass 3
8 23 32 45 78 56
After pass 4
8 23 32 45 56 78
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
Mergesort - Analysis
–
i
2
= m*2m i 0
= m*2m – 2m – 1
Using m = log n
= n * log2n – n – 1
O (n * log2n )
Copy Right: Staffordshire University
Mergesort – Analysis
• Mergesort is extremely efficient algorithm with
respect to time.
– Both worst case and average cases are O (n * log2n )
Partition
• 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.
Copy Right: Staffordshire University
Partition – Choosing the pivot
• First, we have to select a pivot element among the elements
of the given array, and we put this pivot into the first location
of the array before partitioning.
• Which array item should be selected as pivot?
– Somehow we have to select a pivot, and we hope that we
will get a good partitioning.
– If the items in the array arranged randomly, we choose a
pivot randomly.
– We can choose the first or last element as a pivot (it may
not give a good partitioning).
– We can use different techniques to select the pivot.
Copy Right: Staffordshire University
Partition Function
template <class DataType>
void partition(DataType theArray[], int first, int
last,
int &pivotIndex) {
// Partitions an array for quicksort.
// Precondition: first <= last.
// Postcondition: Partitions theArray[first..last] such that:
// S1 = theArray[first..pivotIndex-1] < pivot
// theArray[pivotIndex] == pivot
// S2 = theArray[pivotIndex+1..last] >= pivot
// Calls: choosePivot and swap.
swaps outside of the for loop swaps inside of the for loop
Quicksort – Analysis
Quicksort – Analysis