File tree Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Expand file tree Collapse file tree 1 file changed +39
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ void insertionSort (int array[], int size)
4
+ {
5
+ int i = 0 , tempElement = 0 , j = 0 ;
6
+ for (i = 1 ; i < size; i++)
7
+ {
8
+ tempElement = array[i]; // Choosing element whose correct index to be found.
9
+ j = i - 1 ;
10
+ while (j >= 0 && array[j] > tempElement)
11
+ {
12
+ array[j + 1 ] = array[j]; // Shifting element one position right side untill we get correct position
13
+ j = j - 1 ;
14
+ }
15
+ array[j + 1 ] = tempElement; // got the correct position for tempElement
16
+ }
17
+ }
18
+ void display (int array[], int size)
19
+ {
20
+ int i = 0 ;
21
+ for (i = 0 ; i < size; i++)
22
+ cout << array[i] << " " ;
23
+ cout << endl;
24
+ }
25
+ int main ()
26
+ {
27
+ int size;
28
+ cout<<" Enter the size of the array :" <<endl;
29
+ cin>>size; // size of the array
30
+ int array[size];
31
+ cout<<" Enter array elements" <<endl;
32
+ for (int i=0 ;i<size;i++)
33
+ cin>>array[i]; // taking input
34
+ cout << " unsorted array is :" << endl;
35
+ display (array, size); // display unsorted array
36
+ insertionSort (array, size);
37
+ cout << " sorted array is :" << endl;
38
+ display (array, size); // display the sorted array
39
+ }
You can’t perform that action at this time.
0 commit comments