-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathinsertion_sort.cpp
More file actions
39 lines (30 loc) · 789 Bytes
/
insertion_sort.cpp
File metadata and controls
39 lines (30 loc) · 789 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
#include <iostream>
using namespace std;
// Function to perform Insertion Sort
void insertionSort(int arr[], int n) {
for(int i = 1; i < n; i++) {
int key = arr[i]; // element to insert
int j = i - 1;
// Move elements greater than key
while(j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key; // insert at correct position
}
}
int main() {
int n;
cout << "Enter number of elements: ";
cin >> n;
int* arr = new int[n];
cout << "Enter elements:\n";
for(int i = 0; i < n; i++)
cin >> arr[i];
insertionSort(arr, n);
cout << "Sorted array: ";
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
delete[] arr;
return 0;
}