-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.cpp
More file actions
85 lines (78 loc) · 2.04 KB
/
Copy pathInsertionSort.cpp
File metadata and controls
85 lines (78 loc) · 2.04 KB
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <iostream>
using namespace std;
template <class I>
class insertionSort {
I array[20], n;
public:
void display(I array[20], int n);
void sort(I array[20], int n);
};
template <class I>
void insertionSort<I>::sort(I array[], int n) {
int i, j, comparison = 0, sum = 0;
I temp;
for (i = 1; i < n; i++) {
temp = array[i];
j = i - 1;
comparison++;
while (j >= 0 && array[j] > temp) {
if (array[j - 1] > array[j]) {
comparison++;
}
array[j + 1] = array[j];
j = j - 1;
}
array[j + 1] = temp;
}
cout << "\nComparison: " << comparison;
}
template <class I>
void insertionSort<I>::display(I array[], int n) {
cout << "Array: ";
for (int i = 0; i < n; i++)
cout << array[i] << " ";
}
int main() {
insertionSort<int> obj1;
insertionSort<char> obj2;
int choice, size, array[20];
char a[20];
cout << "Integer" << endl;
cout << "Character" << endl;
cout << "Enter your choice : ";
cin >> choice;
switch (choice) {
case 1:
cout << "Enter size: ";
cin >> size;
cout << "Enter the elements: ";
for (int i = 0; i < size; i++) {
cin >> array[i];
}
obj1.display(array, size);
obj1.sort(array, size);
cout << endl;
cout << "\nSorted Array: " << endl;
obj1.display(array, size);
cout << endl;
break;
case 2:
cout << "Enter size: ";
cin >> size;
cout << "Enter the elements: ";
for (int i = 0; i < size; i++) {
cin >> a[i];
}
obj2.display(a, size);
obj2.sort(a, size);
cout << endl;
cout << "\nSorted Array:" << endl;
obj2.display(a, size);
cout << endl;
break;
default:
cout << "Error wrong choice :(";
break;
}
return 0;
}