123k views
5 votes
Write a C++ program that usesInsertion Sort to sort an unsorted list of numbers.

User Peppo
by
6.6k points

1 Answer

1 vote

C++ program - Insertion sort

#include <bits/stdc++.h>

using namespace std;

/* Defining function for sorting numbers*/

void insertionSort(int array[], int n)

{

int i, k, a;

for(i=1;i<n;i++)

{

k=array[i];

a=i-1;

while(a>=0 && array[a] > k) // moving elements of array[0 to i-1] are greater than k, to one position //

{

array[a+1] = array[a];

a =a-1;

}

array[a+1] =k;

}

}

/* Driver function */

int main()

{

int array[] = { 12,56,76,43,21}; //input integers

int n = sizeof(array) / sizeof(array[0]); //finding size of array

insertionSort(array, n); //Calling function

for (int i = 0; i < n; i++) //printing sorted array

cout << array[i] << " ";

cout << endl;

return 0;

}

User Cherryann
by
6.0k points