File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+
2+ // This is a program on the insertion sort. It's a sorting algorithm.
3+ // -----------Time complexity of the insertion sort algorithm----------
4+ // 1. Best complexity: n
5+ // 2. Average complexity: n^2
6+ // 3. Worst complexity: n^2
7+ // -----------Space complexity of the insertion sort algorithm---------
8+ // 1.Space complexity: 1
9+
10+
11+ #include < bits/stdc++.h>
12+ using namespace std ;
13+
14+ // function to print the elements of the array
15+ void display (int arr[], int n) {
16+
17+ for (int i=0 ;i<n;i++){
18+ cout<<arr[i]<<" " ;
19+ }
20+ printf (" \n " );
21+ }
22+
23+ // function to sort the elements of the array
24+ void insertionSort (int arr[], int n) {
25+ for (int i = 1 ; i < n; i++) {
26+
27+ int temp = arr[i];
28+ int j = i - 1 ;
29+
30+ while (temp < arr[j] && j >= 0 ) {
31+ arr[j + 1 ] = arr[j];
32+ --j;
33+ }
34+ arr[j + 1 ] = temp;
35+ }
36+ }
37+
38+ int main () {
39+
40+ int n;
41+ cout<<" Enter number of elements : " ;
42+ cin>>n;
43+
44+ int arr[n];
45+ cout<<" Enter the array elements :\n " ;
46+ for (int i=0 ;i<n;i++)
47+ {
48+ cin>>arr[i];
49+ }
50+
51+ cout<<" \n Before Sort the array is :\n " ;
52+ display (arr,n);
53+
54+ insertionSort (arr, n);
55+
56+ cout<<" \n After Insertion Sort the array is :\n " ;
57+ display (arr,n);
58+
59+ return 0 ;
60+
61+ }
You can’t perform that action at this time.
0 commit comments