Lila25mila
Lila25milaFeb. 26, 2019, 3:30 a.m.

Insertion sorting algorithm

This description is intended to help you understand what the insertion sort algorithm is and how to implement it in programming.


Technical details, properties, and comparison with other sorting algorithms are out of the question here. If you know what the insertion sort algorithm is, visit this page for insertion sort properties and comparisons with other sorting algorithms.

How does the insertion sort algorithm work?

Algorithm explanations:


Suppose you want to sort the elements in ascending order as shown in the image above. Then the following steps are performed:

  • Step 1: The second element of the array is compared with the elements that appear before it (in this case, only the first element). If the second element is less than the first element, the second element is inserted at the position of the first element. After the first step, the first two elements of the array will be sorted.
  • Step 2: The third element of the array is compared with the elements that appear before it (the first and second element). If the third element is less than the first, it is inserted at the position of the first element. If the third element is greater than the first element but less than the second element, it is inserted at the position of the second element. If the third element is greater than both elements, it stays in the same position. After the second step, the first three elements of the array will be sorted.
  • Step 3: Similarly, the fourth element of the array is compared with the elements that appear before it (first, second and third element) and the same procedure is applied and this element is inserted in the correct position. After the third step, the first four elements of the array will be sorted.

If there are n elements to sort, then this procedure is repeated n-1 times to get a sorted array list.

Sort elements of a C program using the insert sorting algorithm
/*Сортировка элементов массива в порядке возрастания с использованием алгоритма сортировки вставками*/
#include<stdio.h>
int main()
{
    int data[100],n,temp,i,j;
    printf("Enter number of terms(should be less than 100): ");
    scanf("%d",&n);
    printf("Enter elements: ");
    for(i=0;i<n;i++)
    {
        scanf("%d",&data[i]);
    }
    for(i=1;i<n;i++)
    {
        temp = data[i];
        j=i-1;
        while(temp<data[j] && j>=0)
/*Чтобы отсортировать элементы в порядке убывания, измените temp <data [j] на temp> data [j] в строке выше.*/
        {
            data[j+1] = data[j];
            --j;
        }
        data[j+1]=temp;
    }
    printf("In ascending order: ");
    for(i=0; i<n; i++)
        printf("%d\t",data[i]);
    return 0;
}

Note: Although this program is written in C, the insertion sort algorithm can be used similarly in other programming languages.

Output on display:

Enter number of terms(should be less than 100): 5
Enter elements: 12
1
2
5
3
In ascending order: 1     2     3     5     12

Here is another source code that uses the same insertion sort algorithm technique to sort the elements of an array.

/ * Этот исходный код также является реализацией алгоритма сортировки вставками для сортировки элементов массива. * /
/ * Эта программа немного сложна, поскольку содержит несколько циклов. * /
/ * Программа для сортировки массива в порядке убывания * /
#include <stdio.h>
int main()
{
    int data[100],n,i,j,hold,k;
    printf("Enter number of terms(should be less than 100): ");
    scanf("%d",&n);
    printf("Enter elements: ");
    for(i=0;i<=n-1;++i)
    {
       scanf("%d",&data[i]);
    }
    for(i=1;i<=n-1;++i)
    {
    for(j=0;j<i;++j)
       if(data[j]<data[i])
/ * Чтобы отсортировать элементы в порядке возрастания, измените <на> в строке выше. * /
       {
           hold=data[i];
           k=i;
           while(k!=j)
           {
               data[k]=data[k-1];
               --k;
           }
           data[j]=hold;
       }
    }
    printf("In descending Order: ");
    for(i=0;i<=n-1;++i)
     {
       printf("%d    ",data[i]);
    }
    return 0;
}
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
г
  • ги
  • April 23, 2024, 3:51 p.m.

C++ - Test 005. Structures and Classes

  • Result:41points,
  • Rating points-8
l
  • laei
  • April 23, 2024, 9:19 a.m.

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:10points,
  • Rating points-10
l
  • laei
  • April 23, 2024, 9:17 a.m.

C++ - Тест 003. Условия и циклы

  • Result:50points,
  • Rating points-4
Last comments
k
kmssrFeb. 8, 2024, 6:43 p.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 10:30 a.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 8:38 a.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 18, 2023, 9:01 p.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
G
GarApril 22, 2024, 5:46 a.m.
Clipboard Как скопировать окно целиком в clipb?
DA
Dr Gangil AcademicsApril 20, 2024, 7:45 a.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 6:41 a.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 2:35 a.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 4:47 a.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks