-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtriInsert.cpp
More file actions
91 lines (82 loc) · 1.95 KB
/
triInsert.cpp
File metadata and controls
91 lines (82 loc) · 1.95 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
86
87
88
89
90
91
#include <iostream>
using namespace std;
void triInsert(int *&, int &, int &);
void insert(int [], int, int, int);
void displayVec(int [], int);
int findPosition(int [], int, int);
void resizeArray(int *&, int &, int);
int main()
{
int tabSize = -1;
int value;
int *tab = nullptr;
char decision = 'y';
do
{
cout << "Enter the size of your vector: ";
cin >> tabSize;
} while (tabSize <= 0);
tab = new int[tabSize];
int currentSize = 0;
for (int i = 0; i < tabSize; i++) {
cout << "Position " << i + 1 << ": ";
cin >> value;
triInsert(tab, currentSize, value);
}
cout << "++++++++ Here is your sorted vector:" << endl;
displayVec(tab, currentSize);
do
{
cout << "\nContinue to insert? (y or n): ";
cin >> decision;
if (decision == 'y')
{
cout << "Enter your value: ";
cin >> value;
triInsert(tab, currentSize, value);
}
cout << "++++++ The new vector ++++++" << endl;
displayVec(tab, currentSize);
} while (decision == 'y');
delete[] tab;
}
void insert(int vec[], int n, int value, int position)
{
for (int i = n; i > position; i--)
{
vec[i] = vec[i - 1];
}
vec[position] = value;
}
int findPosition(int vec[], int n, int value)
{
for (int i = 0; i < n; i++) {
if (vec[i] > value) {
return i;
}
}
return n;
}
void triInsert(int *&tab, int &n, int &value)
{
resizeArray(tab, n, n + 1);
int position = findPosition(tab, n, value);
insert(tab, n, value, position);
n++;
}
void resizeArray(int *&tab, int ¤tSize, int newSize)
{
int *newTab = new int[newSize];
for (int i = 0; i < currentSize; i++)
{
newTab[i] = tab[i];
}
delete[] tab;
tab = newTab;
}
void displayVec(int vec[], int n)
{
for (int i = 0; i < n; i++)
cout << vec[i] << " ";
cout << endl;
}