
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting Techniques in C Language
In this article, we are going to learn about the different sorting techniques and their implementations in C language. Sorting in C programming requires rearranging elements in the array into a determined order, i.e., in ascending or descending order. This will use the comparison operator to specify the new order of a list or array. This is widely used in different applications that include searching algorithms, data structure optimization, and database management. The following are the sorting techniques that we can implement with C language and other programming also:
Bubble Sort using C
Bubble Sort is an elementary sorting algorithm, which works by repeatedly exchanging adjacent elements, if necessary. When no exchanges are required, the file is sorted.
This is simple and comparison based algorithm that repeats the steps through a list that compares the adjacent elements and replaces them when they are in the wrong order. This process will be continued until the list is sorted.
Example of Bubble Sort using C
The following example repeatedly compares and swaps adjacent elements if they are in the wrong order. This process will be continued until no swaps are needed, indicating that the array is sorted.
#include <stdio.h> void bubbleSort(int array[], int size){ for(int i = 0; i<size; i++) { int swaps = 0; //flag to detect any swap is there or not for(int j = 0; j<size-i-1; j++) { if(array[j] > array[j+1]) { //when the current item is bigger than next int temp; temp = array[j]; array[j] = array[j+1]; array[j+1] = temp; swaps = 1; //set swap flag } } if(!swaps) break; // No swap in this pass, so array is sorted } } int main(){ int n; n = 5; int arr[5] = {67, 44, 82, 17, 20}; //initialize an array printf("Array before Sorting: "); for(int i = 0; i<n; i++) printf("%d ",arr[i]); printf("
"); bubbleSort(arr, n); printf("Array after Sorting: "); for(int i = 0; i<n; i++) printf("%d ", arr[i]); printf("
"); }
Output
This will generate the following result ?
Array before Sorting: 67 44 82 17 20 Array after Sorting: 17 20 44 67 82
Insertion Sort using C
Insertion sort is a very simple method to sort numbers in an ascending or descending order. This method follows the incremental method. It can be compared with the technique how cards are sorted at the time of playing a game.
Insertion is a sorting algorithm that arranges numbers in either ascending or descending order. It follows an incremental approach, similar to how elements are sorted one by one.
Example of Insertion Sort using C
This C program implements Insertion Sort to sort an array of integers. It irritates through the array, taking each element and inserting it into a correct position among the sorted elements.
#include <stdio.h> void insertionSort(int array[], int size){ int key, j; for(int i = 1; i<size; i++) { key = array[i];//take value j = i; while(j > 0 && array[j-1]>key) { array[j] = array[j-1]; j--; } array[j] = key; //insert in right place } } int main(){ int n; n = 5; int arr[5] = {67, 44, 82, 17, 20}; // initialize the array printf("Array before Sorting: "); for(int i = 0; i<n; i++) printf("%d ",arr[i]); printf("
"); insertionSort(arr, n); printf("Array after Sorting: "); for(int i = 0; i<n; i++) printf("%d ", arr[i]); printf("
"); }
Output
The code is generated as follows ?
Array before Sorting: 67 44 82 17 20 Array after Sorting: 17 20 44 67 82
Selection Sort using C
Selection sort is a simple sorting algorithm. This sorting algorithm, like insertion sort, is an in-place comparison-based algorithm in which the list is divided into two parts, the sorted part at the left end and the unsorted part at the right end. Initially, the sorted part is empty and the unsorted part is the entire list.
Example of Selection Sort using C
The following C program implements Selection Sort to sort an array of integers. This function repeatedly finds that the minimum elements from the unsorted part of the array and swaps it with the first unsorted element. This process continues until the entire array is sorted.
#include <stdio.h> void selectionSort(int array[], int size){ int i, j, imin; for(i = 0; i<size-1; i++) { imin = i; //get index of minimum data for(j = i+1; j<size; j++) if(array[j] < array[imin]) imin = j; //placing in correct position int temp; temp = array[i]; array[i] = array[imin]; array[imin] = temp; } } int main(){ int n; n = 5; int arr[5] = {12, 19, 55, 2, 16}; // initialize the array printf("Array before Sorting: "); for(int i = 0; i<n; i++) printf("%d ",arr[i]); printf("
"); selectionSort(arr, n); printf("Array after Sorting: "); for(int i = 0; i<n; i++) printf("%d ", arr[i]); printf("
"); }
Output
The output is obtained as follows ?
Array before Sorting: 12 19 55 2 16 Array after Sorting: 2 12 16 19 55
Merge Sort using C
Merge sort is a sorting technique based on divide and conquer technique. With worst-case time complexity being ?(n log n), it is one of the most used and approached algorithms.
Example of Merge Sort using C
This C program implements Merge Sort to sorts an array of integers. It divides the array into two equal halves, sorts each half iteratively and merges the sorted halves. The merging function combines two sorted subarrays into one. Th program prints the array before and after sorting to illustrate the changes.
#include <stdio.h> #define max 10 int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 }; int b[10]; void merging(int low, int mid, int high){ int l1, l2, i; for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) { if(a[l1] <= a[l2]) b[i] = a[l1++]; else b[i] = a[l2++]; } while(l1 <= mid) b[i++] = a[l1++]; while(l2 <= high) b[i++] = a[l2++]; for(i = low; i <= high; i++) a[i] = b[i]; } void sort(int low, int high){ int mid; if(low < high) { mid = (low + high) / 2; sort(low, mid); sort(mid+1, high); merging(low, mid, high); } else { return; } } int main(){ int i; printf("Array before sorting
"); for(i = 0; i <= max; i++) printf("%d ", a[i]); sort(0, max); printf("
Array after sorting
"); for(i = 0; i <= max; i++) printf("%d ", a[i]); }
Output
The result is generated as follows ?
Array before sorting 10 14 19 26 27 31 33 35 42 44 0 Array after sorting 0 10 14 19 26 27 31 33 35 42 44
Shell Sort using C
Shell sort is a highly efficient sorting algorithm and is based on insertion sort algorithm. This algorithm avoids large shifts as in case of insertion sort, if the smaller value is to the far right and has to be moved to the far left.
Example of Shell Sort using C
Shell Sort sorts an array of integers by starting with a large gap and reducing it by half with each iteration. Elements are compared and swapped if necessary. This process continues until the gap is 1. This program prints the array before and after sorting to show the changes.
#include <stdio.h> void shellSort(int arr[], int n){ int gap, j, k; for(gap = n/2; gap > 0; gap = gap / 2) { //initially gap = n/2, decreasing by gap /2 for(j = gap; j<n; j++) { for(k = j-gap; k>=0; k -= gap) { if(arr[k+gap] >= arr[k]) break; else { int temp; temp = arr[k+gap]; arr[k+gap] = arr[k]; arr[k] = temp; } } } } } int main(){ int n; n = 5; int arr[5] = {33, 45, 62, 12, 98}; // initialize the array printf("Array before Sorting: "); for(int i = 0; i<n; i++) printf("%d ",arr[i]); printf("
"); shellSort(arr, n); printf("Array after Sorting: "); for(int i = 0; i<n; i++) printf("%d ", arr[i]); printf("
"); }
Output
The result is obtained as follows ?
Array before Sorting: 33 45 62 12 98 Array after Sorting: 12 33 45 62 98
Heap Sort using C
Heap Sort is an efficient sorting technique based on the heap data structure. It works by building a max heap from the input data, then repeatedly extracting the maximum elements from the heap and rebuilding the heap until all the elements are sorted.
Example of Heap Sort using C
In the below example, we implement Heap Sort to sort an array of integers from the list. It firsts builds a max heap from the input array, then repeatedly swaps the root with the last element and reduces the heap size while maintaining the heap property. Following example prints the array before and after sorting to illustrate the changes.
#include <stdio.h> void heapify(int[], int); void build_maxheap(int heap[], int n){ int i, j, c, r, t; for (i = 1; i < n; i++) { c = i; do { r = (c - 1) / 2; if (heap[r] < heap[c]) { // to create MAX heap array t = heap[r]; heap[r] = heap[c]; heap[c] = t; } c = r; } while (c != 0); } printf("Heap array: "); for (i = 0; i < n; i++) printf("%d ", heap[i]); heapify(heap, n); } void heapify(int heap[], int n){ int i, j, c, root, temp; for (j = n - 1; j >= 0; j--) { temp = heap[0]; heap[0] = heap[j]; // swap max element with rightmost leaf element heap[j] = temp; root = 0; do { c = 2 * root + 1; // left node of root element if ((heap[c] < heap[c + 1]) && c < j-1) c++; if (heap[root]<heap[c] && c<j) { // again rearrange to max heap array temp = heap[root]; heap[root] = heap[c]; heap[c] = temp; } root = c; } while (c < j); } printf("
The sorted array is: "); for (i = 0; i < n; i++) printf("%d ", heap[i]); } int main(){ int n, i, j, c, root, temp; n = 5; int heap[10] = {2, 3, 1, 0, 4}; // initialize the array build_maxheap(heap, n); }
Output
The result is obtained as follows ?
Heap array: 4 3 1 0 2 The sorted array is: 0 1 2 3 4
Bucket Sort using C
Bucket Sort algorithm is similar to the Counting Sort algorithm, as it is just the generalized form of the counting sort. Bucket sort assumes that the input elements are drawn from a uniform distribution over the interval [0, 1).
Example of Bucket Sort using C
This C program implements Bucket Sort to sort an array of integers. It finds the maximum number of elements that initializes a count array, and counts occurrences of each element. The elements are then placed back into the original array in sorted order. This program prints the array before and after sorting to illustrate the changes.
#include <stdio.h> void bucketsort(int a[], int n){ // function to implement bucket sort int max = a[0]; // get the maximum element in the array for (int i = 1; i < n; i++) if (a[i] > max) max = a[i]; int b[max], i; for (int i = 0; i <= max; i++) { b[i] = 0; } for (int i = 0; i < n; i++) { b[a[i]]++; } for (int i = 0, j = 0; i <= max; i++) { while (b[i] > 0) { a[j++] = i; b[i]--; } } } int main(){ int a[] = {12, 45, 33, 87, 56, 9, 11, 7, 67}; int n = sizeof(a) / sizeof(a[0]); // n is the size of array printf("Before sorting array elements are:
"); for (int i = 0; i < n; ++i) printf("%d ", a[i]); bucketsort(a, n); printf("
After sorting array elements are:
"); for (int i = 0; i < n; ++i) printf("%d ", a[i]); }
Output
The ouput is produced as follows ?
Before sorting array elements are: 12 45 33 87 56 9 11 7 67 After sorting array elements are: 7 9 11 12 33 45 56 67 87
Counting Sort Using C
Counting sort is an external sorting algorithm that assumes all the input values are integers that lie between the range 0 and k. Then mathematical computations on these input values to place them at the correct position in the output array.
Example of Counting Sort using C
This C program implements Counting Sort to Sort an array of integers. It initializes a count array to store the frequency of each element in the array, calculates the cumulative count, and then places elements in their correct positions in the output array. This program prints the array before and after sorting the illustrating the changes.
#include<stdio.h> int countingsort(int a[], int n){ int i, j; int output[15], c[100]; for (i = 0; i < 100; i++) c[i] = 0; for (j = 0; j < n; j++) ++c[a[j]]; for (i = 1; i <= 99; i++) c[i] += c[i-1]; for (j = n-1; j >= 0; j--) { output[c[a[j]] - 1] = a[j]; --c[a[j]]; } printf("
After sorting array elements are: "); for (i = 0; i<n; i++) printf("%d ", output[i]); } void main(){ int n , i; int a[] = {12, 32, 44, 8, 16}; n = sizeof(a) / sizeof(a[0]); printf("Before sorting array elements are: "); for(int i = 0; i<n; i++){ printf("%d " , a[i]); } countingsort(a, n); }
Output
The result is generated as follows ?
Before sorting array elements are: 12 32 44 8 16 After sorting array elements are: 8 12 16 32 44
Radix Sort Using C
Radix sort is a step-wise sorting algorithm that starts the sorting from the least significant digit of the input elements. Like Counting Sort and Bucket Sort, Radix sort also assumes something about the input elements, that they are all k-digit numbers.
Example of Radix Sort using C
This C program implements Radix sort to sort an array of integers. It Sorts the array by processing each digit of the numbers, starting from the least significant digit to the most significant. The countsort function is used to sort the digits at each position. The program prints the array before and after sorting to illustrate the changes.
#include <stdio.h> void countsort(int a[], int n, int pos){ int output[n + 1]; int max = (a[0] / pos) % 10; for (int i = 1; i < n; i++) { if (((a[i] / pos) % 10) > max) max = a[i]; } int count[max + 1]; for (int i = 0; i < max; ++i) count[i] = 0; for (int i = 0; i < n; i++) count[(a[i] / pos) % 10]++; for (int i = 1; i < 10; i++) count[i] += count[i - 1]; for (int i = n - 1; i >= 0; i--) { output[count[(a[i] / pos) % 10] - 1] = a[i]; count[(a[i] / pos) % 10]--; } for (int i = 0; i < n; i++) a[i] = output[i]; } void radixsort(int a[], int n){ int max = a[0]; for (int i = 1; i < n; i++) if (a[i] > max) max = a[i]; for (int pos = 1; max / pos > 0; pos *= 10) countsort(a, n, pos); } int main(){ int a[] = {236, 15, 333, 27, 9, 108, 76, 498}; int n = sizeof(a) / sizeof(a[0]); printf("Before sorting array elements are: "); for (int i = 0; i <n; ++i) { printf("%d ", a[i]); } radixsort(a, n); printf("
After sorting array elements are: "); for (int i = 0; i < n; ++i) { printf("%d ", a[i]); } printf("
"); }
Output
The above code generates the following result ?
Before sorting array elements are: 236 15 333 27 9 108 76 498 After sorting array elements are: 9 15 27 76 108 236 333 498
Quick Sort Using C
Quick sort is a highly efficient sorting algorithm and is based on partitioning of array of data into smaller arrays. A large array is partitioned into two arrays one of which holds values smaller than the specified value, say pivot, based on which the partition is made and another array holds values greater than the pivot value.
Example of Quick Sort using C
This code implements the Quick Sort algorithm. It sorts an array by selecting a pivot, partitioning the array into elements i.e., less than and greater than the pivot, and recursively sorting the subarrays. The partition function handles the rearrangement, while quicksort recursively sorts the sub arrays. The display function prints the array, and swaps exchanges elements.
#include <stdio.h> #include <stdbool.h> #define MAX 7 int intArray[MAX] = { 4,6,3,2,1,9,7 }; void printline(int count) { int i; for (i = 0; i < count - 1; i++) { printf("="); } printf("=
"); } void display() { int i; printf("["); // navigate through all items for (i = 0; i < MAX; i++) { printf("%d ", intArray[i]); } printf("]
"); } void swap(int num1, int num2) { int temp = intArray[num1]; intArray[num1] = intArray[num2]; intArray[num2] = temp; } int partition(int left, int right, int pivot) { int leftPointer = left - 1; int rightPointer = right; while (true) { while (intArray[++leftPointer] < pivot) { //do nothing } while (rightPointer > 0 && intArray[--rightPointer] > pivot) { //do nothing } if (leftPointer >= rightPointer) { break; } else { printf(" item swapped :%d,%d
", intArray[leftPointer], intArray[rightPointer]); swap(leftPointer, rightPointer); } } printf(" pivot swapped :%d,%d
", intArray[leftPointer], intArray[right]); swap(leftPointer, right); printf("Updated Array: "); display(); return leftPointer; } void quickSort(int left, int right) { if (right - left <= 0) { return; } else { int pivot = intArray[right]; int partitionPoint = partition(left, right, pivot); quickSort(left, partitionPoint - 1); quickSort(partitionPoint + 1, right); } } int main() { printf("Input Array: "); display(); printline(50); quickSort(0, MAX - 1); printf("Output Array: "); display(); printline(50); }
Output
The above code generates the following result ?
Input Array: [4 6 3 2 1 9 7 ] ================================================== pivot swapped :9,7 Updated Array: [4 6 3 2 1 7 9 ] pivot swapped :4,1 Updated Array: [1 6 3 2 4 7 9 ] item swapped :6,2 pivot swapped :6,4 Updated Array: [1 2 3 4 6 7 9 ] pivot swapped :3,3 Updated Array: [1 2 3 4 6 7 9 ] Output Array: [1 2 3 4 6 7 9 ] ==================================================