0% found this document useful (0 votes)
3 views2 pages

Practical Number 7

Uploaded by

17.vikashverma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views2 pages

Practical Number 7

Uploaded by

17.vikashverma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

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

You might also like