DS - Arrays
DS - Arrays
DS - Arrays
data structure
0 1 2 3 4 5 6
What’s Special About Arrays?
0 1 2 3 4 5 6
What’s Special About Arrays?
Constant-time access
0 1 2 3 4 5 6
What’s Special About Arrays?
Constant-time access
array_addr
0 1 2 3 4 5 6
What’s Special About Arrays?
Constant-time access
array_addr + elem_size × ( )
0 1 2 3 4 5 6
What’s Special About Arrays?
Constant-time access
array_addr + elem_size × (i − first_index)
0 1 2 3 4 5 6
Multi-Dimensional Arrays
Multi-Dimensional Arrays
(0, 0)
Multi-Dimensional Arrays
(2,3)
Multi-Dimensional Arrays
(2,3)
(2 − 0) × 6
Multi-Dimensional Arrays
(2,3)
(2 − 0) × 6 + (3 − 0)
Multi-Dimensional Arrays
(2,3)
(2,3)
array_addr +
elem_size × ((2 − 0) × 6 + (3 − 0))
Address Calculation in one Dimensional Array
Address Calculation in one Dimensional Array
Index 1 2 3 4 5 6 7 8 9 10
Valu
10 15 2 35 60 45
e
Insertion at the middle
Index 1 2 3 4 5 6 7 8 9 10
Value 10 15 2 35 60 45
↪
Index 1 2 3 4 5 6 7 8 9 10
Value 10 15 2 35 60 45
↪
Index 1 2 3 4 5 6 7 8 9 10
Value 10 15 2 35 60 45
↪
After Insertion
Index 1 2 3 4 5 6 7 8 9 10
Value 10 15 2 100 35 60 45
Algorithm to insert an element in Array
1. Set I:=N
2. Repeat the step 3 and 4 while I>=LOC
3. Set DATA[I+1]:=DATA[I]
4. I=I-1
[End of loop]
5. Set DATA[I]=ELEMENT
6. N=N+1
7. Exit
Deletion Operation
Index 1 2 3 4 5 6 7 8 9 10
Value 10 15 20 35 60 45
↩
Deletion
Index 1 2 3 4 5 6 7 8 9 10
Value 10 20 35 60 45
Index 1 2 3 4 5 6 7 8 9 10
Value 10 20 35 60 45
↩
Deletion
Index 1 2 3 4 5 6 7 8 9 10
Value 10 20 35 60 45
After Deletion
Index 1 2 3 4 5 6 7 8 9 10
Value 10 20 35 60 45
Algorithm to delete an element from an array
1.Set ELEMENT=DATA[LOC]
2.Repeat for I=LOC to N-1
Set DATA[I]:=DATA[I+1]
[End of loop]
3.N:=N-1
4.Exit
Search Operation
You can perform a search for an array
element based on its value or its index.
Linear search
Linear search /sequential search
#include <stdio.h>
void main() {
int a[] = {1,3,5,7,8};
int item = 7, n = 5;
int i = 0, j = 0;
j = j + 1;
}
void main() {
int a[] = {1,3,5,7,8};
int item = 7, n = 5, k=3,x=10;
int i = 0, j = 0;
}
Output
The original array elements are :
a[0] = 1
a[1] = 3
a[2] = 5
a[3] = 7
a[4] = 8
The array elements after updating :
a[0] = 1
a[1] = 3
a[2] = 10
a[3] = 7
a[4] = 8