-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort.cpp
More file actions
44 lines (37 loc) · 779 Bytes
/
insertion_sort.cpp
File metadata and controls
44 lines (37 loc) · 779 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n)
{
for (int i = 1; i < n; ++i) {
int temp = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > temp) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = temp;
}
}
void printArray(int arr[], int n)
{
cout << "The sorted array is : ";
for (int i = 0; i < n; ++i)
cout <<arr[i] << " ";
cout << endl;
}
int main()
{
int n;
cout<<"Enter size of array: ";
cin>>n;
cout<<endl<<"Enter elements of array: ";
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
/* This code is contributed by ShuvoGG */