Life Hacks


      

Write a program of the Insertion Sort.



#include<iostream.h>

#include<conio.h>

void main( ) /* main start */

{

clrscr( );

int a[50], n, i, ptr, temp; /* local variable */

cout << " Enter the number of elements in an array is : ”;

cin >> n; // Enter the no. of elements wants to be sorted.

a[0] = 0;

cout << " Enter the value of elements of array is : ";

for(i = 1; i <= n; i++) // Entering value of elements of an array.

{

cin >> a[i];

} /* End of for loop*/

for(i = 2; i <= n; i++) // sorting elements of the array by using insertion sort.

{

temp = a[i];

ptr = i – 1;

while(temp <= a[ptr])

{

a[ptr + 1] = a[ptr];

ptr = ptr – 1;

} /* End of while loop*/

a[ptr + 1] = temp;

} /* End of for loop*/

cout << " \n Sorted array is: ";

for(i = 1; i <= n; i++) // displays sorted elements of array.

{

cout <<" \n " <<a[i];

} /* End of for loop*/

getch( );

}

Output:-

clip_image002

Leave a Reply