0% found this document useful (0 votes)
9 views

4 Insertation Sort

Uploaded by

Tanvir Anan
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)
9 views

4 Insertation Sort

Uploaded by

Tanvir Anan
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

Insertion Sort

Insertion Sort Insertion sort is based on the idea that one element from the input
elements is consumed in each iteration to find its correct position i.e, the position to
which it belongs in a sorted array. It iterates the input elements by growing the
sorted array at each iteration. It compares the current element with the largest
value in the sorted array. If the current element is greater, then it leaves the
element in its place and moves on to the next element else it finds its correct
position in the sorted array and moves it to that position. This is done by shifting all
the elements, which are larger than the current element, in the sorted array to one
position ahead.
Pseudocode for Insertion Sort
INSERTION-SORT(A)
for j = 2 to n
key ← A [j]
j←i–1
while i > 0 and A[i] > key
A[i+1] ← A[i]
i←i–1
A[j+1] ← key

C++ Code to Implement Insertion Sort


#include <iostream>
using namespace std;
void Swap(int *x, int *y)
{
int temp = *x;
* x = *y;
* y = temp;
}
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j]; j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray(int arr[], int n) {
int i;
for (i=0; i < n; i++)
cout<<arr[i]<<" "; cout<<endl;
}
int main() {
int n,x,i;
cout<<"Enter size of array: "; cin>>n;
int arr[n];
cout<<"Enter Array Elements: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
insertionSort(arr,n);
printArray(arr,n);
return 0;
}

You might also like