Sorting
Sorting
// 1. allocate node
Node* new_node = new Node();
// 2. put in the data
new_node->data = new_data;
// 3. Make next of new node as head
new_node->next = (*head_ref);
// 4. Move the head to point to
// the new node
(*head_ref) = new_node;
}
Sorting:
A Sorting Algorithm is used to rearrange a given array or list of elements according to a comparison
operator on the elements. The comparison operator is used to decide the new order of elements in the
respective data structure.
Bubble Sort:
Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements
if they are in the wrong order. This algorithm is not suitable for large data sets as its average and
worst-case time complexity is quite high.
Write a program for Bubble Sort.
#include <stdbool.h>
#include <stdio.h>
void swap(int* xp, int* yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
// An optimized version of Bubble Sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
for (i = 0; i < n - 1; i++) {
swapped = false;
for (j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
swapped = true;
}
}
#include <bits/stdc++.h>
using namespace std;
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int N = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, N);
printArray(arr, N);
return 0;
}
Complexity Analysis of Insertion Sort:
Time Complexity of Insertion Sort
The worst-case time complexity of the Insertion sort is O(N^2)
The average case time complexity of the Insertion sort is O(N^2)
The time complexity of the best case is O(N).
Space Complexity of Insertion Sort
The auxiliary space complexity of Insertion Sort is O(1)
Characteristics of Insertion Sort
This algorithm is one of the simplest algorithms with a simple implementation
Basically, Insertion sort is efficient for small data values
Insertion sort is adaptive in nature, i.e. it is appropriate for data sets that are already partially
sorted.
Other Fact about Insertion Sort
Insertion sort takes the maximum time to sort if elements are sorted in reverse order. And it
takes minimum time (Order of n) when elements are already sorted.
The Insertion Sort algorithm follows an incremental approach.
Yes, insertion sort is an in-place sorting algorithm.
Insertion sort is used when number of elements is small. It can also be useful when the input
array is almost sorted, and only a few elements are misplaced in a complete big array.
Quick Sort Algorithm
QuickSort is a Divide and Conquer algorithm. It picks an element as a pivot and partitions the given
array around the pivot. There are many different versions of quickSort that pick the pivot in different
ways.
Always pick the first element as a pivot.
Always pick the last element as a pivot.
Pick a random element as a pivot.
Pick the median as the pivot.
Quick Sort by picking the first element as the Pivot.
The key function in quick sort is a partition. The target of partitions is to put the pivot in its correct
position if the array is sorted and the smaller (or equal) to its left and higher elements to its right and
do all this in linear time.
Partition Algorithm:
We start from the leftmost element and keep track of the index of smaller (or equal) elements
as i.
While traversing, if we find a smaller (or equal) element, we swap the current element with
arr[i].
Otherwise, we ignore the current element.
/* This function takes first element as pivot, places the pivot element at its correct position in
sorted array, and places all smaller (smaller than or equal to pivot) to left of pivot and all
greater elements to right of pivot */
partition (arr[], low, high) {
// first element as pivot
pivot = arr[low]
k = high
for (i = high; i > low; i–) {
if (arr[i] > pivot){
swap arr[i] and arr[k];
k–;
}
}
swap arr[k] and arr[low]
return k-1;
}
// Driver Code
int main()
{
int arr[] = { 7, 6, 10, 5, 9, 2, 1, 15, 7 };
int n = sizeof(arr) / sizeof(arr[0]);
quickSort(arr, 0, n - 1);
cout << "Sorted array: \n";
printArray(arr, n);
return 0;
}
Complexity Analysis:
Time Complexity:
Average Case: O(N * logN), where N is the length of the array.
Best Case: O(N * logN)
Worst Case: O(N2)
Auxiliary Space: O(1)
Merge Sort
Merge sort is defined as a sorting algorithm that works by dividing an array into smaller subarrays,
sorting each subarray, and then merging the sorted subarrays back together to form the final sorted
array.
“Merge sort is a recursive algorithm that continuously splits the array in half until it cannot be
further divided i.e., the array has only one element left (an array with one element is always sorted).
Then the sorted subarrays are merged into one sorted array”.
// C program for Merge Sort
#include <stdio.h>
#include <stdlib.h>
merge(arr, l, m, r);
}
}
// Driver code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int arr_size = sizeof(arr) / sizeof(arr[0]);
Heap Sort:
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to
the selection sort where we first find the minimum element and place the minimum element at the
beginning. Repeat the same process for the remaining elements.
// left = 2*i + 1
int left = 2 * i + 1;
// right = 2*i + 2
int right = 2 * i + 2;
largest = left;
largest = right;
swap(&arr[i], &arr[largest]);
heapify(arr, N, i);
// Heap sort
for (int i = N - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
// Driver's code
int main()
{
int arr[] = { 12, 11, 13, 5, 6, 7 };
int N = sizeof(arr) / sizeof(arr[0]);
// Function call
heapSort(arr, N);
printf("Sorted array is\n");
printArray(arr, N);
}