Download C++ Array Traversal and Insertion/Deletion Algorithms and more Lab Reports Data Structures and Algorithms in PDF only on Docsity!
LAB SESSION 02
- Let an array named LA consist of 4 elements 2, 4, 6 & 8. Write down the code to traverse (or print) all elements in the array.
CODE:
#include using namespace std; int main() { int LA [4] = {2,4,6,8}; int start = 0, N = 4; while(start<N) { cout<<"The element present at index "<<start<<" is "<<LA[start]<<endl; start = start + 1; } return 0; }
OUTPUT:
- Use insertion algorithm to add an element (Give implementation)
i. 1 at index 0
CODE:
#include using namespace std; int main() { int LA [4] = {2,4,6,8}, k, item, j, i, N = 4; cout<<"enter the item to insert: "; cin>>item; cout<<"enter the index no to insert: "; cin>>k; j=N-1; While (j>=k) { LA[j+1]=LA[j]; j=j-1; } LA[k]=item; N=N+1; // print the updated array for (i = 0; i < N; i++) cout << LA[i] << " "; cout << endl; return 0; }
cout << LA[i] << " "; cout << endl; return 0; }
OUTPUT:
iii. 3 at index 4
CODE:
#include using namespace std; int main() { int LA [4] = {2,4,6,8}, k, item, j, i, N = 4; cout<<"enter the item to insert: "; cin>>item; cout<<"enter the index no to insert: "; cin>>k; j=N-1; While (j>=k) { LA[j+1]=LA[j]; j=j-1;
LA[k]=item; N=N+1; // print the updated array for (i = 0; i < N; i++) cout << LA[i] << " "; cout << endl; return 0; }
OUTPUT:
- If the size of given array is 4 then calculate the Time complexity of insertion algorithm when ,
- Insert element at the beginning of array
- Insert element at the end of array
- Insert element in the middle of array Location of insertion At the beginning of array At the end of array At the middle of array Number of iteration 4 1 2 Big o notation O(n) O(1) O(n)
- Consider the array in question 2, Use deletion algorithm (Give implementation) to remove an element
OUTPUT:
ii. 5 at index 2
CODE:
#include using namespace std; int main() { int LA [5] = {2,4,6,8,3}; int k, item, j, i, N = 4; cout<<"enter the item to delete: "; cin>>item; cout<<"enter the position to delete an item: "; cin>>k; j=k; while(j<N) { LA[j]=LA[j+1]; j=j+1; } N=N-1; // print the updated array
for (i = 0; i < N+1; i++) cout << LA[i] << " "; cout << endl; return 0; }
OUTPUT:
iii. 3 at index 4
CODE:
#include using namespace std; int main() { int LA [5] = {2,4,6,8,3}; int k, item, j, i, N = 4; cout<<"enter the item to delete: "; cin>>item; cout<<"enter the position to delete an item: "; cin>>k; j=k; while(j<N)