Practical Number: 7
Write a program to sort an array of integers in ascending order using Insertion
sort.
Sol: Insertion sort is a simple sorting algorithm that works similar to the way you
sort playing cards in your hands. The array is virtually split into a sorted and an
unsorted part. Values from the unsorted part are picked and placed at the correct
position in the sorted part.
#include<iostream>
using namespace std;
void insertionSort(int arr[], int n){
for(int i=1; i<n; i++){
int ptr= arr[i];
int j= i-1;
while(arr[j] > ptr && j>=0){
arr[j+1] = arr[j];
j--;
}
arr[j+1]= ptr;
}
}
int main(){
int n;
cout<<"Enter number of element in array : ";
cin>>n;
18
int arr[n];
cout<<endl<<"Enter element in array : ";
for(int i=0; i<n; i++){
cin>>arr[i];
}
insertionSort(arr,n);
cout<<endl<<"Array after sorting : ";
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
return 0;
}
Output:
19