ch04 Sorting Methods
ch04 Sorting Methods
These algorithms are known as the quadratic algorithms because their Big
O time complexity is O(n2).
Principle (3/3):
In the first iteration, we place the largest element at the end of
the array.
For the next iteration, we are therefore no longer obliged to
make a comparison with the last element.
So at each iteration, the number of values to compare
decreases by 1.
Bubble Sort
Illustration of the principle: Consider the following elements: 6
0 3 5 1 4 2, We want to sort these values in ascending order.
First passage:
}
}
}
Selection Sort
The principle of this algorithm is to:
Find the largest element, place it at the end of the array, start over
with the second largest, place it before the last position and so on
until you have gone through the entire array.
It is the same idea on how you pick your cards from the
table, and you then place them in their position.
Principle:
Compare the second element with the first one. If it is greater,
then place it after the first element.
Take the third element and compare it with the elements on
the left of it. Placed it just behind the element smaller than it.
Insertion Sort: Example
Initial array:
Step 1:
Insertion Sort: Example
Step 2: Step 3:
Insertion Sort: Example
Step 4:
Insertion Sort: Code
Void insertSort(int a[ ], int size){
int i,j, key;
for( i=0;i<n;i++){
key=a[i];
for(j=i;j>0 && a[j-1]>key;j--){
a[ j ]=a[j-1]; // shifting the position to the right
}
a[ j ]=key;
}
}
QuickSort
QuickSort is a Divide and Conquer algorithm. It picks an
element as pivot and partitions the given array around the
picked pivot.
j = 5 : Since arr[j] <= pivot, do i++ and swap arr[i] with arr[j]
i = 3 arr[] = {10, 30, 40, 50, 80, 90, 70} // 90 and 50 Swapped
QuickSort
We come out of loop because j is now equal to high-1.
Finally we place pivot at correct position by swapping arr[i+1]
and arr[high] (or pivot)
arr[] = {10, 30, 40, 50, 70, 90, 80} // 80 and 70 Swapped Now 70
is at its correct place.
All elements smaller than 70 are before it and all elements
greater than 70 are after it.
Partition Code:
QuickSort
The main function that implements QuickSort:
MergeSort
Like quicksort, merge sort is a divide and conquer
algorithm.
It divides input array in two halves, calls itself for the two
halves and then merges the two sorted halves.
4 0 6 1 5 2 3
4 0 6 1 5 2
40 04 61 16 52 25 3
Mergesort(0,6)
0 1 4 6 2 3 5
Merge(0,3,6)
Mergesort(4,6)
Mergesort(0,3)
Merge(4,5,6)
Mergesort(6,6)
Mergesort(4,5)
Mergesort(0,1)
Mergesort(2,3)
Merge(0,1,3)
0 1 2 3 4 5 6 Mergesort(5,5)
Merge(4,4,5)
Merge(0,0,1)
Mergesort(1,1)
Mergesort(0,0)
Mergesort(3,3)
Mergesort(2,2)
Merge(2,2,3)
Mergesort(4,4)
MergeSort Algorithm