chapter 2 array data structure winter 2004. array the array is the most commonly used data storage...
TRANSCRIPT
Array
• The Array is the most commonly used Data Storage Structure.
• It’s built into most Programming languages.
Creating an Array
• An array is a sequential data abstrction, its name is a reference to an array.
int[ ] intArray; //defines a reference to an array
intArray = new int[100]; //creates the array
INSERTION
• Example of insert operation and behavior
– New Item always inserted in the first vacant cell in the array.
• Observations:– Most algorithm knows how many items are
already in the array.– Searching and deleting are however not fast.
DELETING
• Example of delete operation and behavior
– To delete an element first, you must find it.– How long does it take for the worst case?– A deletion requires searching through an
average of N/2 elements and moving the rest of the elements.
INITIALIZATION
• In Java, an array of integers is automatically initialized to 0.
• Unless you specify otherwise,
• You can initialize an array to something beside 0 using this syntax:
int[] intArray ={0,1,2,3,4,5,6,7,8,9};
Accessing Array Elements
• Array elements are accessed using an index number.
temp = intArray[3]; //get 4th element content
intArray[7] = 66;//insert 66 in eighth cell
Linear Search
• What is Linear search?
• Simple-minded way= a sequential search
• N elements array– What is the worst case?– Run time is O (N)
Binary Search
• What is Binary search?– A sorted array is required
• New insert()
• Searching a sorted array by repeatedly dividing the search interval in half.
• Run time is O (log N)
logarithms
Range Comparisons in B-search
10 4 (2 3 = 8)
1000 10
10,000 14
:
:
1,000,000,000 30
Power of Two: 2s -> s + 1 steps
Complexity of algorithm
• Time complexity
• Space complexity
• Time complexity: in big O notation. How much time it takes to process N data elements? Ignore constant details
Complexity of algorithm
for i = 1 to nIf a[i] == x then return a[i]Else i++;
endfor
• What is the complexity?for i = 1 to n
for j = 1 to m If a[i, j] == x then return a[i] else i++;
endforendfor
Complexity of algorithm
• Don’t need constant since N can be very large
– O(N) - worst case for a linear search in an array
– O(N2)– O(log N)
Complexity of algorithm
Example of algorithm Big O
Linear search
Binary Search
Insertion for unordered array
Insertion for ordered array
Deletion for unordered array
Deletion for ordered array