
- C Programming Tutorial
- C - Home
- C - Overview
- C - Environment Setup
- C - Program Structure
- C - Basic Syntax
- C - Data Types
- C - Variables
- C - Constants
- C - Storage Classes
- C - Operators
- C - Decision Making
- C - Loops
- C - Functions
- C - Scope Rules
- C - Arrays
- C - Pointers
- C - Strings
- C - Structures
- C - Unions
- C - Bit Fields
- C - Typedef
- C - Input & Output
- C - File I/O
- C - Preprocessors
- C - Header Files
- C - Type Casting
- C - Error Handling
- C - Recursion
- C - Variable Arguments
- C - Memory Management
- C - Command Line Arguments
- C Programming useful Resources
- C - Questions & Answers
- C - Quick Guide
- C - Useful Resources
- C - Discussion
Explain the insertion sort by using C language.
Sorting is the process of arranging the elements either in ascending (or) descending order.
Types of sorting
C language provides five sorting techniques, which are as follows −
- Bubble sort (or) Exchange Sort
- Selection sort
- Insertion sort(or) Linear sort
- Quick sort (or) Partition exchange sort
- Merge Sort (or) External sort
Insertion Sort
The logic used to sort the elements by using the insertion sort technique is as follows −
for(i = 1; i <= n - 1; i++){ for(j = i; j > 0 && a[j - 1] > a[j]; j--){ t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; } }
Explanation
Let us consider some elements which are in unsorted order −
Example
Following is the C program to sort the elements by using the insertion sort technique −
#include<stdio.h> int main() { int a[50], i,j,n,t; printf("enter the No: of elements in the list:
"); scanf("%d", &n); printf("enter the elements:
"); for(i=0; i<n; i++){ scanf ("%d", &a[i]); } for(i = 1; i <= n - 1; i++){ for(j=i; j > 0 && a[j - 1] > a[j]; j--){ t = a[j]; a[j] = a[j - 1]; a[j - 1] = t; } } printf ("after insertion sorting the elements are:
"); for (i=0; i<n; i++) printf("%d\t", a[i]); return 0; }
Output
When the above program is executed, it produces the following output −
Enter the No: of elements in the list: 10 Enter the elements: 34 125 2 6 78 49 1 3 89 23 After insertion sorting the elements are: 1 2 3 6 23 34 49 78 89 125
- Related Articles
- Explain insertion of elements in linked list using C language
- Insertion sort using C++ STL
- Explain the quick sort technique in C language.
- Explain the merge sort technique in C language
- Insertion Sort in C#
- Insertion Sort List C++
- Explain the procedure of selection sort in C language
- Explain the stack by using linked list in C language
- Explain queue by using linked list in C language
- Binary Insertion Sort in C++
- Insertion Sort List in C++
- C++ Program Recursive Insertion Sort
- Insertion Sort
- Explain bit field in C language by using structure concept
- C++ Program to Implement Insertion Sort

Advertisements