Lecture 02 - Arrays (Autosaved)
Lecture 02 - Arrays (Autosaved)
Arrays
Gayana Fernando
LO2 : Design algorithms for solving problems that use data structure Array
LO4: Develop the ability to compare and contrast the performance of data structures.
• Introduction
• Array
Implementation
• Array Algorithms
0 1 2 3 4 5 6
Value Value Value Value Value Value Value
01 02 03 04 05 06 07
Elements
SLIIT Academy Pvt Ltd. © 2022 8
Array Index
• Array declaration:
anyType [] arrayName;
• Like other objects, the declaration creates only a reference, initially set to null.
An array must be created before it can be used.
• One way to create an array:
arrayName = new anyType [length];
arrName d.v.
d.v.
d.v.
d.v
numberList maxSize
count
02: Constructer
0
myArray maxSize
1 5
2
3
0 index
4
03: Insert a Value
0
myArray maxSize
1 5
2
3
0 index
4
60,50,10
03: Delete a Value
0 60
myArray maxSize
1 50
5
2 10
3
3 index
4
60,50,10
Ordered Arrays
0 1 2 3
10 20 30 40
Ordered Arrays
• Modify the insert method.
• Need to find the correct location (above the smaller value and lower the
larger value).
• Move all the larger values to get space.
03: Insert a Value
0 60
myArray maxSize
1 5
2
3
0 index
4
60,50,10,40
public void addValue(int value)
{
int i;
for(i = 0;i < count; i++)
{
if(numberList[i] > value) {
break;
}
}
for(int j = count; j > i; j--)
{
numberList[j]= numberList[j-1];
}
nunberList[i] = value;
count++;
}
Ordered Arrays - Searching a
value
• We can use “Binary Search” algorithm to look for a value in
an ordered array.
• Searching is efficient in ordered arrays.
Arrays
Advantages Disadvantages
• Accessing /Searching a value is • Fixed Size
easy • Inserting / deleting to ordered
• Implementation is simple array are not efficient.
Array – efficiency
• If the array contains N elements
• Inserting a new element will take O(n) time
• Searching / Deleting
• Worst case – O(n)
• Best case – O(1)