forked from avastino7/Algorithms-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 1
/
InsertionSort.cpp
53 lines (41 loc) · 1 KB
/
InsertionSort.cpp
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
45
46
47
48
49
50
51
52
53
#include <iostream>
#include <conio.h>
using namespace std;
void insertionSort_forLoop(int arr[], int n) {
for(int i=1; i<n; i++) {
int temp=arr[i], j;
for(j=i-1; j>=0; j--) {
if(arr[j] > temp) {
arr[j+1] = arr[j];
} else {
break;
}
}
arr[j+1] = temp;
}
}
void insertionSort_whileLoop(int arr[], int n) {
for(int i=1; i<n; i++) {
int temp=arr[i], j=i-1;
while(arr[j]>temp && j>=0) {
arr[j+1] = arr[j];
j--;
}
arr[j+1] = temp;
}
}
int main() {
int arr[100], n;
cout<<"Enter the size of array: ";
cin>>n;
cout<<"Enter the elements of the array: ";
for(int i=0; i<n; i++) {
cin>>arr[i];
}
insertionSort_forLoop(arr, n);
cout<<"The sorted array is: ";
for(int i=0; i<n; i++) {
cout<<arr[i]<<" ";
}
return 0;
}