Lecture 9: Sorting
Md. Nazmul Abdal
Lecturer
Department of CSE
University of Liberal Arts Bangladesh (ULAB)
Bubble Sort
⚫ Bubble sort is a sorting algorithm that compares two adjacent
elements and swaps them until they are in the intended order.
Algorithm
LinearSearch(array, key)
for each item in the array
if item == value
return its index
Bubble Sort
Bubble Sort
Bubble Sort
Bubble Sort
Selection Sort
⚫ Selection sort is a sorting algorithm that selects the smallest element
from an unsorted list in each iteration and places that element at the
beginning of the unsorted list.
Algorithm
selectionSort(array, size)
repeat (size - 1) times
set the first unsorted element as the minimum
for each of the unsorted elements
if element < currentMinimum
set element as new minimum
swap minimum with first unsorted position
end selectionSort
Selection Sort
Selection Sort
Selection Sort
Selection Sort
Implementation
#include <stdio.h> // function to print an array
// function to swap the the position of two elements void printArray(int array[], int size) {
void swap(int *a, int *b) { for (int i = 0; i < size; ++i) {
int temp = *a; printf("%d ", array[i]);
*a = *b; }
*b = temp; printf("\n");
} }
void selectionSort(int array[], int size) {
for (int step = 0; step < size - 1; step++) { // driver code
int min_idx = step; int main() {
for (int i = step + 1; i < size; i++) { int data[] = {20, 12, 10, 15, 2};
// To sort in descending order, change > to < in this line. int size = sizeof(data) / sizeof(data[0]);
// Select the minimum element in each loop. selectionSort(data, size);
if (array[i] < array[min_idx]) printf("Sorted array in Acsending Order:\n");
min_idx = i; printArray(data, size);
} }
// put min at the correct position
swap(&array[min_idx], &array[step]);
}
}
Insertion Sort
⚫ Insertion sort is a sorting algorithm that places an unsorted element
at its suitable place in each iteration.
Algorithm
insertionSort(array)
mark first element as sorted
for each unsorted element X
'extract' the element X
for j <- lastSortedIndex down to 0
if current element j > X
move sorted element to the right by 1
break loop and insert X here
end insertionSort
Insertion Sort
Insertion Sort
Insertion Sort
Insertion Sort
Implementation
#include <stdio.h>
// Function to print an array
// Driver code
void printArray(int array[], int size) {
int main() {
for (int i = 0; i < size; i++) {
int data[] = {9, 5, 1, 4, 3};
printf("%d ", array[i]);
int size = sizeof(data) / sizeof(data[0]);
}
insertionSort(data, size);
printf("\n");
printf("Sorted array in ascending order:\n");
}
printArray(data, size);
void insertionSort(int array[], int size) {
}
for (int step = 1; step < size; step++) {
int key = array[step];
int j = step - 1;
// Compare key with each element on the left of it until an element smaller than
// it is found.
// For descending order, change key<array[j] to key>array[j].
while (key < array[j] && j >= 0) {
array[j + 1] = array[j];
--j;
}
array[j + 1] = key;
}
}
Merge Sort
⚫ Merge Sort is one of the most popular sorting algorithms that is
based on the principle of Divide and Conquer Algorithm.
⚫ Here, a problem is divided into multiple sub-problems. Each sub-
problem is solved individually. Finally, sub-problems are combined
to form the final solution.
Algorithm
MergeSort(A, p, r):
if p > r
return
q = (p+r)/2
mergeSort(A, p, q)
mergeSort(A, q+1, r)
merge(A, p, q, r)
Merge Sort
Implementation
#include <stdio.h> // Until we reach either end of either L or M, pick larger among
// Merge two subarrays L and M into arr // elements L and M and place them in the correct position at A[p..r]
void merge(int arr[], int p, int q, int r) { while (i < n1 && j < n2) {
if (L[i] <= M[j]) {
// Create L ← A[p..q] and M ← A[q+1..r] arr[k] = L[i];
int n1 = q - p + 1; i++;
int n2 = r - q; } else {
int L[n1], M[n2]; arr[k] = M[j];
j++;
for (int i = 0; i < n1; i++) }
L[i] = arr[p + i]; k++;
for (int j = 0; j < n2; j++) }
M[j] = arr[q + 1 + j]; // When we run out of elements in either L or M,
// pick up the remaining elements and put in A[p..r]
// Maintain current index of sub-arrays and main array while (i < n1) {
int i, j, k; arr[k] = L[i];
i = 0; i++;
j = 0; k++;
k = p; }
Implementation
while (j < n2) {
// Print the array
arr[k] = M[j];
void printArray(int arr[], int size) {
j++;
for (int i = 0; i < size; i++)
k++;
printf("%d ", arr[i]);
}
printf("\n");
}
}
// Divide the array into two subarrays, sort them and merge them
// Driver program
void mergeSort(int arr[], int l, int r) {
int main() {
if (l < r) {
int arr[] = {6, 5, 12, 10, 9, 1};
int size = sizeof(arr) / sizeof(arr[0]);
// m is the point where the array is divided into two subarrays
int m = l + (r - l) / 2;
mergeSort(arr, 0, size - 1);
mergeSort(arr, l, m);
printf("Sorted array: \n");
mergeSort(arr, m + 1, r);
printArray(arr, size);
}
// Merge the sorted subarrays
merge(arr, l, m, r);
}
}
Quick Sort
⚫ Quicksort is a sorting algorithm based on the divide and conquer
approach where
⚫ An array is divided into subarrays by selecting a pivot element
(element selected from the array).
⚫ While dividing the array, the pivot element should be positioned in
such a way that elements less than pivot are kept on the left side and
elements greater than pivot are on the right side of the pivot.
⚫ The left and right subarrays are also divided using the same
approach. This process continues until each subarray contains a
single element.
⚫ At this point, elements are already sorted. Finally, elements are
combined to form a sorted array.
Quick Sort
Algorithm
quickSort(array, leftmostIndex, rightmostIndex)
if (leftmostIndex < rightmostIndex)
pivotIndex <- partition(array,leftmostIndex, rightmostIndex)
quickSort(array, leftmostIndex, pivotIndex - 1)
quickSort(array, pivotIndex, rightmostIndex)
partition(array, leftmostIndex, rightmostIndex)
set rightmostIndex as pivotIndex
storeIndex <- leftmostIndex - 1
for i <- leftmostIndex + 1 to rightmostIndex
if element[i] < pivotElement
swap element[i] and element[storeIndex]
storeIndex++
swap pivotElement and element[storeIndex+1]
return storeIndex + 1
Quick Sort
Quick Sort
Quick Sort
Quick Sort
Quick Sort
Quick Sort
Quick Sort
Implementation
#include <stdio.h>
// swap element at i with element at j
// function to swap elements
swap(&array[i], &array[j]);
void swap(int *a, int *b) {
}
int t = *a;
}
*a = *b;
// swap the pivot element with the greater element at i
*b = t;
swap(&array[i + 1], &array[high]);
}
// return the partition point
// function to find the partition position
return (i + 1);
int partition(int array[], int low, int high) {
}
// select the rightmost element as pivot
void quickSort(int array[], int low, int high) {
int pivot = array[high];
if (low < high) {
// pointer for greater element
int i = (low - 1);
// find the pivot element such that
// traverse each element of the array
// elements smaller than pivot are on left of pivot
// compare them with the pivot
// elements greater than pivot are on right of pivot
for (int j = low; j < high; j++) {
int pi = partition(array, low, high);
if (array[j] <= pivot) {
// if element smaller than pivot is found
// swap it with the greater element pointed by i
i++;
Implementation
// recursive call on the left of pivot // main function
quickSort(array, low, pi - 1); int main() {
int data[] = {8, 7, 2, 1, 0, 9, 6};
// recursive call on the right of pivot
quickSort(array, pi + 1, high); int n = sizeof(data) / sizeof(data[0]);
}
} printf("Unsorted Array\n");
// function to print array elements printArray(data, n);
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) { // perform quicksort on data
printf("%d ", array[i]); quickSort(data, 0, n - 1);
}
printf("\n"); printf("Sorted array in ascending order: \n");
} printArray(data, n);
}
Thank You