C++ Program to sort an array using Insertion Sort
Program
#include<iostream>
#define SIZE 10
using namespace std;
void insertionSort(int count, int a[])
{
int i, j, temp;
for (i = 0; i < count; i++)
{
temp = a[i];
j = i - 1;
while ((temp < a[j]) && (j >= 0))
{
a[j + 1] = a[j];
j = j - 1;
}
a[j + 1] = temp;
}
printf("Sorted Elements:\n");
for (i = 0; i < count; i++)
cout << a[i] << endl;
}
int main()
{
int count, i;
int a[SIZE];
cout << "Enter the size of the array:\t";
cin >> count;
cout << "Enter " << count << " elements:\n";
for (i = 0; i < count; i++)
cin >> a[i];
insertionSort(count, a);
}
Output
Enter the size of the array: 6
Enter 6 elements:
87
12
0
85
75
32
Sorted Elements:
0
12
32
75
85
87