140 likes | 251 Vues
Learn the fundamentals of arrays, from storing data to advanced operations. Find, manipulate, and process data efficiently in array structures. Understand array characteristics and work with static arrays effectively. Practice essential array algorithms such as iteration, reversal, and searching for both numerical and string arrays. Improve your coding skills and master basic algorithms on arrays with practical examples and exercises. Prepare yourself for linear and binary search challenges.
E N D
Learning Objectives • Arrays are useful for storing data in a linear structure • We learn how to process data stored in an array • We learn how to • Read a file and store a set of Strings in an array • We learn how to find a specific String in an array • We learn how to find ALL Strings that starts with a prefix String • And more……
We recall an Array Characteristics - A contiguous block of memory spaces - Each one is referred to by an index - indices start from 0 and go to n-1 - Array is “homogeneous” , that is, it can only keep one type of data
Define and initialize an array int[ ] A = new int[10]; A[0] = 10; A[1] = 20; …..
Arrays are Static Once defined Size cannot be changed A A.length = 20; /* illegal */ Why? Because a Static Memory Block is already allocated and it cannot be changed.
So how do we change size? double the size Define a new array B of double the size int[ ] B = new int[2*A.length];for (inti=0; i<A.length; i++){ B[i] = A[i]; } A = B; Iterate through the array A Copy old elements of A to B Discard old A and assign new B to A
Iterate through all elements in the array for (inti =0; i < A.length; i = i + 1) { /* write your code here */ }
Iterate backwards for (inti = A.length-1; i >= 0; i = i - 1) { /* write your code here */ }
Reverse the Array Think of an algorithm to do this
Find the max/min in an Array for (inti = 0; i < A.length ; i = i + 1) { }
Array of Strings for (inti = 0; i < A.length ; i = i + 1) { } Print all Strings starting with prefix
Next • Linear and Binary Search on Arrays