Sorting
Sorting
22 18 12 -4 58 7 31 42
split split split split
22 18 12 -4 58 7 31 42
merge merge merge merge
18 22 -4 12 7 58 31 42
merge merge
-4 12 18 22 7 31 42 58
merge
-4 7 12 18 22 31 42 58
18 22 -4 12
i j
18 22 -4 12
i j
18 22 -4 12 i<= mid
j<=high
i j
-4 12 18 22
Quick Sort
• Quicksort is the widely used sorting algorithm that
makes n*logn comparisons in average case for sorting an array of n
elements.
• It is a faster and highly efficient sorting algorithm.
• This algorithm follows the divide and conquer approach.
• Divide and conquer is a technique of breaking down the algorithms
into subproblems, then solving the subproblems, and combining the
results back together to solve the original problem.
Quick Sort
Quick Sort
int partition (int a[], int start, int end)
{
int pivot = a[end]; // pivot element
/* function to implement quick sort */
int i = (start - 1);
void quick(int a[], int start, int end)
for (int j = start; j <= end - 1; j++)
{
{ // If current element is smaller than the pivot
if (start < end)
if (a[j] < pivot)
{
{ int p = partition(a, start, end); //p is the partitioning index
i++; quick(a, start, p - 1);
int t = a[i]; quick(a, p + 1, end);
a[i] = a[j]; }
a[j] = t; }
}
}
int t = a[i+1];
a[i+1] = a[end];
a[end] = t;
return (i + 1);
}
Heap
• A heap is a tree with some special properties. The basic requirement of a heap is
that the value of a node must be ≥ (or ≤) than the values of its children. This is
called heap property.
Second pass:
11 12 13 5 6
Working of Insertion Sort
Third pass:
11 12 13 5 6
11 12 5 13 6
12 5 12 13 6
5 11 12 13 6
Working of Insertion Sort
Fourth Pass:
5 11 12 13 6
5 11 12 6 13
5 11 6 12 13
5 6 11 12 13
5 6 11 12 13
Working of Insertion Sort
void insertionSort(int arr[], int n)
{ int i, key, j;
for (i = 1; i < n; i++)
{ key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key)
{ arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
Radix Sort
• In Radix sort, there is digit by digit sorting is performed that is started
from the least significant digit to the most significant digit.
Example:
Pass 1:
Example:
Pass 2:
Example:
Pass 3:
Time Complexity of Sorting algorithms
Algorithm Time Complexity
Best Average Worst
Selection Sort Ω(n^2) θ(n^2) O(n^2)
Bubble Sort Ω(n) θ(n^2) O(n^2)
Insertion Sort Ω(n) θ(n^2) O(n^2)
Heap Sort Ω(n log(n)) θ(n log(n)) O(n log(n))
Quick Sort Ω(n log(n)) θ(n log(n)) O(n^2)
Merge Sort Ω(n log(n)) θ(n log(n)) O(n log(n))