Skip to content

Commit eaae2da

Browse files
Insertion Sort in C++
1 parent 3ae7043 commit eaae2da

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

sorting/insertion-sort.cpp

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/*
2+
Copyright (C) Deepali Srivastava - All Rights Reserved
3+
This code is part of DSA course available on CourseGalaxy.com
4+
*/
5+
6+
#include<iostream>
7+
using namespace std;
8+
9+
#define MAX 20
10+
void sort(int a[], int n);
11+
12+
int main()
13+
{
14+
int a[MAX], n;
15+
16+
cout << "Enter the number of elements : ";
17+
cin >> n;
18+
19+
for( int i=0; i<n; i++ )
20+
{
21+
cout << "Enter element " << i+1 << ": " ;
22+
cin >> a[i];
23+
}
24+
25+
sort(a,n);
26+
27+
cout << "Sorted array is : ";
28+
for( int i=0; i<n; i++ )
29+
cout << a[i] << " ";
30+
cout << "\n";
31+
}
32+
33+
void sort(int a[], int n)
34+
{
35+
int i, j, temp;
36+
37+
for( i=1; i<n; i++ )
38+
{
39+
temp = a[i];
40+
41+
for( j=i-1; j>=0 && a[j]>temp; j-- )
42+
a[j+1] = a[j];
43+
a[j+1] = temp;
44+
}
45+
}
46+
47+

0 commit comments

Comments
 (0)