-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquestion18.cpp
67 lines (53 loc) · 1.3 KB
/
question18.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
54
55
56
57
58
59
60
61
62
63
64
65
66
#include<iostream>
using namespace std;
class InsertionSort {
private:
int* array;
int size;
int comparisonCount;
public:
InsertionSort(int arr[], int n) : size(n), comparisonCount(0) {
array = new int[size];
for (int i = 0; i < size; ++i) {
array[i] = arr[i];
}
}
~InsertionSort() {
delete[] array;
}
void sort() {
for (int i = 1; i < size; ++i) {
int key = array[i];
int j = i - 1;
while (j >= 0 && array[j] > key) {
array[j + 1] = array[j];
comparisonCount++;
j--;
}
array[j + 1] = key;
}
}
void display() {
cout << "Sorted Array: ";
for (int i = 0; i < size; ++i) {
cout << array[i] << " ";
}
cout << endl;
cout << "Number of comparisons: " << comparisonCount << endl;
}
};
int main() {
int size;
cout << "Enter the size of the array: ";
cin >> size;
int* arr = new int[size];
cout << "Enter the elements of the array:\n";
for (int i = 0; i < size; ++i) {
cin >> arr[i];
}
InsertionSort insertionSorter(arr, size);
insertionSorter.sort();
insertionSorter.display();
delete[] arr;
return 0;
}