-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlab_session_insert_applyTo_sorted_Array.txt
More file actions
71 lines (58 loc) · 1.74 KB
/
lab_session_insert_applyTo_sorted_Array.txt
File metadata and controls
71 lines (58 loc) · 1.74 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
#include <iostream>
using namespace std;
// Assume that you want insert 25 into array : 10,20,30,40
void insert(int a[], int *size, int newn) // *size : is The current number of elements in the array (not the array's total capacity).
{
//When newn is greater than the last element in the array:
if(newn>a[*size])
{
*size=*size+1;
a[*size]=newn;
}
else
{
*size=*size+1;
for(int i=*size-1; i>=0;i--)
{
a[i+1]=a[i];
if(i==0)
a[i]=newn;
else if(newn>=a[i-1])
{
a[i]=newn;
break;
}
}
}
}
int main(void)
{
int a[10]={10,20,30,40};
int size=3, newNumber;
cout<<"Enter new number"<<endl;
cin>>newNumber;
insert(a, &size, newNumber);
for (int i = 0; i <= size; i++) {
cout << a[i] << " ";
}
cout << endl;
return 0;
}
-------------------------------------------------------------------
For deletion :
**************
void deletion(int a[], int *size, int oldn)
{
for(int i = 0; i <= *size; i++) // Loop through all elements in the array
{
if (oldn == a[i]) // If the current element is equal to the element to be removed
{
// Move all elements after the one to be removed one position left
for(int j = i; j <= *size; j++) // Start from the index of the deleted element
a[j] = a[j+1]; // Shift the next element to the left
i--; // Decrement `i` to stay at the current index for the next iteration (to handle duplicate values)
*size = *size - 1; // Decrease the size of the array (since we removed one element)
}
}
// a[*size + 1] = 0; // This is a comment, but if needed, it would set the last element to 0 after the deletion.
}