Array
Array
rd
ARRAYS
Definition
• Array which can hold a fix number of items and these
items should be of the same type. Most of the data
structures make use of arrays to implement their
algorithms.
• Row Major
LOC(LA[i][j])=Base(LA)+w[N(i-1)+(j-1)]
• Column Major
LOC(LA[j][i])=Base(LA)+w[M(j-1)+(i-1)]
Array operations
• Traverse − print all the array elements one by one.
• Insertion − Adds an element at the given index.
• Deletion − Deletes an element at the given index.
• Search − Searches an element using the given
index or by the value.
• Update − Updates an element at the given index.
Insertion Operation
• Insert operation is to insert one or more data
elements into an array. Based on the
requirement, a new element can be added at
the beginning, end, or any given index of
array.
Algorithm of Insertion Let LA be a Linear Array (unordered) with N elements
K is a positive integer such that K<=N.
Following is the algorithm where ITEM is inserted into the Kth position of LA
1. Set ITEM:=LA[K]
2. Repeat for J=K to N-1
Set LA[J] := LA[J+1] [Move J+1st element upward]
[End of Loop]
3. Set N := N-1 [Reset N]
4. Exit
Algorithm of Searching Consider LA is a linear array with N elements
K is a positive integer such that K<=N.
Following is the algorithm to find an element with a value of ITEM using
sequential search.
1. Set J = 0
2. Repeat steps 3 and 4 while J < N
3. IF LA[J] is equal ITEM THEN GOTO STEP 5
4. Set J = J +1
[End of loop]
5. PRINT J, ITEM
6. Exit
Update Program
void main()
{int a[10],k, item, n, i, j;
cout<<"enter no of elements:\n";
cin>>n;
for(i =0; i<n; i++)
{ cin>>a[i]; }
for(i = 0; i<n; i++)
{ cout<<a[i]; }
cout<<"enter position:\n";
cin>>k;
cout<<"enter item:";
cin>>item;
for(i=0;i<n;i++)
{ a[k]=item; }
cout<<"The array elements after updation :\n";
for(i = 0; i<n; i++)
{cout<<a[i];}
Sparse Matrix
• A matrix is a two-dimensional data object made
of m rows and n columns, therefore having
total m x n values. If most of the elements of
the matrix have 0 value, then it is called a
sparse matrix.
00304
00570
00000
02600
Why to use Sparse Matrix instead of simple matrix ?