on Leave a Comment

C++ Program for Insertion Sort

This c++ program sorts an array of n elements using insertion sort technique. In this program, first you have to enter size of an array, then you have to enter elements of array using keyboard and finally sorted array is displayed on the screen.

C++ Program for Insertion Sort

#include<iostream>
using namespace std;
void insertionSort(int arr[], int size);
int main()
{
        int arr[50], n, i, j;
        cout<<"Enter Array Size : ";
        cin>>n;
        cout<<"Enter Array Elements : ";
        for(i=0; i<n; i++)
        {
                cin>>arr[i];
        }
        insertionSort(arr, n);
        return 0;
}
void insertionSort(int arr[], int size)
{
    int i, j, temp;
    for(i=1; i<size; i++)
        {
                temp=arr[i];
                j=i-1;
                while((temp<arr[j]) && (j>=0))
                {
                        arr[j+1]=arr[j];
                        j=j-1;
                }
                arr[j+1]=temp;
        }
        cout<<"Sorted Array : ";
        for(i=0; i<size; i++)
        {
                cout<<arr[i]<<"  ";
        }
}

OUTPUT:

Enter Array Size : 5
Enter Array Elements : 9 8 4 2 7
Sorted Array : 2  4  7  8  9

See also:


0 comments:

Post a Comment