14
Basic Algorithms on Arrays

Basic Algorithms on Arrays

  • Upload
    elisa

  • View
    18

  • Download
    0

Embed Size (px)

DESCRIPTION

Basic Algorithms on Arrays. 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 - PowerPoint PPT Presentation

Citation preview

Page 1: Basic Algorithms on Arrays

Basic Algorithms on Arrays

Page 2: Basic Algorithms on Arrays

Learning ObjectivesArrays are useful for storing data in a linear

structureWe learn how to process data stored in an

arrayWe 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……

Page 3: Basic Algorithms on Arrays

We recall an Array 10 20 60 30 67 90 76 65 87 07

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

Page 4: Basic Algorithms on Arrays

Define and initialize an array10 20 60 30 67 90 76 65 87 07

int[ ] A = new int[10];A[0] = 10;A[1] = 20;

…..

Page 5: Basic Algorithms on Arrays

Arrays are Static10

20

60

30

67

90

76

65

87

07

Once defined

Size cannot be

changed

A.length = 20; /* illegal */

A

Why?Because a Static Memory Block is already

allocated and it cannot be changed.

Page 6: Basic Algorithms on Arrays

So how do we change size?10

20

60

30

67

90

76

65

87

07

double the size

int[ ] B = new int[2*A.length];for (int i=0; i<A.length; i++){ B[i] = A[i];}A = B;

Define a new array B of double the size

Iterate through the array A

Copy old elements of A to B

Discard old A and assign new B to A

Page 7: Basic Algorithms on Arrays

Operations on Arrays

Page 8: Basic Algorithms on Arrays

Iterate through all elements in the array

10 20 60 30 67 90 76 65 87 07

for (int i =0; i < A.length; i = i + 1) { /* write your code here */ }

Page 9: Basic Algorithms on Arrays

Iterate backwards10 20 60 30 67 90 76 65 87 07

for (int i = A.length-1; i >= 0; i = i - 1) { /* write your code here */ }

Page 10: Basic Algorithms on Arrays

Reverse the Array10 20 60 30 67 90 76 65 87 07

Think of an algorithm to do this

07 87 65 76 90 67 30 60 20 10

Page 11: Basic Algorithms on Arrays

Find the max/min in an Array10 20 60 30 67 90 76 65 87 07

for (int i = 0; i < A.length ; i = i + 1) {

}

Page 12: Basic Algorithms on Arrays

Array of Stringsaaa ade 6as

dbb tr ori

ohelp

me yes no

for (int i = 0; i < A.length ; i = i + 1) {

}

Print allStrings starting

with prefix

Page 13: Basic Algorithms on Arrays

Now to class work

Page 14: Basic Algorithms on Arrays

NextLinear and Binary Search on Arrays