Professional Documents
Culture Documents
4 Arrays
4 Arrays
4 Arrays
Arrays
Arrays
• An array is an ordered list of data values of similar kind.
0 1 2 3 4 5 6 7 8
a 43 56 32 87 46 16 82 51 92
max = a[0]
Update max
Do nothing
max = a[1]
Linear Search
• The most basic operation
• Very easy to implement
• The array DOESN’T have to be sorted
• All array elements must be visited if the search fails
Linear Search Target = 46
0 1 2 3 4 5 6 7 8
a[0] != 46 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8
a[1] != 46 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8
a[2] != 46 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8
a[3] != 46 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8
a[4] == 46 43 56 32 87 46 16 82 51 92
Delete an Element Target = 46
• First, we need to search the element to get the index.
• Shift the elements from next to the index.
• Decrease the size of the array.
0 1 2 3 4 5 6 7 8
a 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8
a 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7
a 43 56 32 87 16 82 51 92
Delete an Element
int trgt = 46, arr_size = 9, i = 0;
while(i < arr_size){
if(a[i] == trgt)
break;
i++;
}
while(i < arr_size-1){
a[i] = a[i+1];
i++;
}
arr_size--;
Insert an Element at Index i
• At first, we need to increase the size of the array.
• Shift all the elements from index i.
• Assign the element at index i.
0 1 2 3 4 5 6 7 8 9
a 43 56 32 87 46 16 82 51 92
0 1 2 3 4 5 6 7 8 9
a 43 56 32 87 46 46 16 82 51 92
0 1 2 3 4 5 6 7 8 9
a 43 56 32 87 71 46 16 82 51 92
Insert an Element at Index i
int arr_size = 9, new_value, i, x;
arr_size++;
scanf(“%d”, &x);
scanf(“%d”, &new_value);
i = x;
while(i < arr_size-1){
a[i+1] = a[i];
i++;
}
a[x] = new_value;
Collecting statistics in an array
• Take N students’ marks as input and store them in array. Find and
print how many of them got A, how many of them got B, C, D and
F grades respectively. The grade chart is provided below:
Marks Grade
===== =====
90 – 100 A
80 – 89 B
70 – 79 C
60 – 69 D
<60 F