-
Notifications
You must be signed in to change notification settings - Fork 1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #22 from Manvi07/master
Added insertion sort in C++
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
/* Insertion Sort implementation in C++ | ||
* Author : Manvi Gupta | ||
* Input : array length and elements | ||
* Output : Sorted array elements | ||
*/ | ||
|
||
#include <iostream> | ||
using namespace std; | ||
|
||
int n; | ||
void insertionSort(int A[]) | ||
{ | ||
int key; | ||
for(int i=0;i<n;i++) | ||
{ | ||
key = A[i]; | ||
int j = i-1; | ||
while(j>=0 and key<A[j]) | ||
{ | ||
A[j+1] = A[j]; | ||
j--; | ||
} | ||
A[j+1]=key; | ||
} | ||
} | ||
|
||
int main() | ||
{ | ||
std::cout << "Enter the array length: "; | ||
std::cin >> n; | ||
int A[n]; | ||
std::cout << "Enter the array elements :" << '\n'; | ||
for(int i=0; i<n; i++) | ||
cin >> A[i]; | ||
insertionSort(A); | ||
std::cout << "Sorted Array :" << '\n'; | ||
for(int i=0;i<n;i++) | ||
cout << A[i] << endl; | ||
return 0; | ||
} |