review 1 arrays & strings array array elements accessing array elements declaring an array...

33
Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure String Array of Strings Examples

Upload: angelina-parrish

Post on 14-Jan-2016

269 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Review

1

Arrays & StringsArray Array ElementsAccessing array elementsDeclaring an arrayInitializing an arrayTwo-dimensional ArrayArray of StructureStringArray of StringsExamples

Page 2: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Searching

Introduction to Searching External and Internal SearchingTypes of Searching

Linear or sequential searchBinary Search

Algorithms for Linear SearchAlgorithms for Binary Search

2

Page 3: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

IntroductionInformation retrieval is one of the most

important applications of computersWe are given a name and are asked for an

associated telephone listingWe are given an account number and are

asked for the transactions occurring in that account

We are given an employee name or number and are asked for the employee records

3

Page 4: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

IntroductionInformation retrieval is one of the most

important applications of computersWe are given a name and are asked for an

associated telephone listingWe are given an account number and are

asked for the transactions occurring in that account

We are given an employee name or number and are asked for the employee records

4

Page 5: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Searching is a process of checking and finding an element from a list of elements

If we want to find the presence of an element “data” in A, then we have to search for it

The search is successful if data does appear in A and unsuccessful otherwise

A question you should always ask when selecting a search algorithm is “How fast does the search have to be?” The reason is that, in general, the faster the algorithm is, the more complex it is.

Bottom line: you don’t always need to use or should use the fastest algorithm5

Page 6: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

KeyIn these examples, we are given one piece

of information, which we shall call a keyWe are asked to find a record that contains

other information associated with the keyWe shall allow both the possibility that

there is more than one record with the same key and that there is no record with the given key

6

Page 7: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Records and their keys

7

Page 8: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

AnalysisSearching for the keys that locate records is often

the most time-consuming action in a programtherefore, the way records are arranged and the

choice of method used for searching can make a substantial difference in the program’s performance

For this reason, we should check that how much work is done by each of the algorithms we develop

We shall find that counting the number of times that one key is compared with another gives us an excellent measure of the total amount of work that the algorithm will do and of the total amount of computer time it will require when it is run

8

Page 9: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

External and Internal SearchingThe searching problem falls naturally into

two casesExternal SearchingIf there are many records, perhaps each

one quite large, then it will be necessary to store the records in files on disk or tape, external to the computer memory

Internal SearchingIn this case, the records to be searched are

stored entirely within the computer memory

9

Page 10: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Types of SearchingThere are two types of searching

techniques:Linear or Sequential SearchingBinary Searching

Linear or Sequential SearchingIn linear search, each element of an array

is read one by one sequentiallyIt is compared with the desired elementA search will be unsuccessful if all the

elements are read and the desired element is not found

10

Page 11: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Sequential Search on an Unordered ListIn this case, we have an unordered list of

items/elementsWe check each and every element in the list

sequentially and it is compared with the desired element

AlgorithmGet the search criterion (key)Get the first record from the fileWhile ( (record != key) and (still more records) )

Get the next recordEnd_whileIf ( record = key )

Then successElse there is no match in the file

End_else11

Page 12: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Sequential Search on an Ordered ListIn this case, we have an ordered list of elementsWe check each and every element in the list

sequentially and it is compared with the desired element

Algorithm:Get the search criterion (key)Get the first record from the fileWhile ( (record < key) and (still more records) )

Get the next recordEnd_whileIf ( record = key )

Then successElse there is no match in the file

End_else

12

Page 13: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Algorithm for Linear SearchLet A be an array of n elements, A[1],A[2],A[3], ...... A[n].

“data” is the element to be searched. Then this algorithm will find the location “loc” of data in A. Set loc = – 1,if the search is unsuccessful.

1. Input an array A of n elements and “data” to be searched and initialize loc = – 1.

2. Initialize i = 0; and repeat through step 3 if (i < n) by incrementing i by one .

3. if (data = A[i])(a) loc = i(b) GOTO step 4

4. if (loc > 0)(a) Display “data is found and searching is successful”

5. else(a) Display “data is not found and searching is unsuccessful”

6. exit13

Page 14: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Sequential Search of Ordered vs. Unordered List

Let’s do a comparison.If the order was ascending alphabetical

on customer’s last names, how would the search for Shahab Ali on the ordered list compare with the search on the unordered list?Unordered list

if Shahab Ali was in the list?if Shahab Ali was not in the list?

Ordered listif Shahab Ali was in the list?if Shahab Ali was not in the list?

14

Page 15: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Ordered vs. Unordered (cont)How about Mohammad Waqas?

Unordered if Mohammad Waqas was in the list? if Mohammad Waqas was not in the list?

Ordered if Mohammad Waqas was in the list? if Mohammad Waqas was not in the list?

15

Page 16: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Ordered vs. Unordered (cont)Observation: the search is faster on an

ordered listAlso, keep in mind that the list has to

first be placed in order for the ordered search.

Conclusion: the efficiency of these algorithms is roughly the same.

So, if we need a faster search, we need a completely different algorithm.

How else could we search an ordered file?

16

Page 17: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Binary SearchSequential search is easy to write and efficient

for short lists, but a disaster for long onesImagine trying to find the name “Ahmad Tahir”

in a large telephone book by reading one name at a time starting at the front of the book

To find any entry in a long list, there are far more efficient methods, provided that the keys in the list are already sorted into order

If we have an ordered list, we can use a different strategy

The binary search gets its name because the algorithm continually divides the list into two parts

17

Page 18: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Binary SearchBinary search is an extremely efficient

algorithm when it is compared to linear searchBinary search technique searches “data” in

minimum possible comparisonsFirst compare the target key with one in the

center of the list and then restrict our attention to only the first or second half of the list, depending on whether the target key comes before or after the central one

With one comparison of keys we thus reduce the list to half its original size

Continuing in this way, at each step, we reduce the length of the list to be searched by half

18

Page 19: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

In only twenty steps, this method will locate any requested key in a list containing more than a million elements

This approach of course requires that the elements in the list already be in completely order

Suppose we have a sorted array of n elements, then apply the following steps to search an element

19

Page 20: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

1. Find the middle element of the array (i.e., n/2 is the middle element if the array or the sub-array contains n elements)

2. Compare the middle element with the data to be searched, then there are following three cases

(a) If it is a desired element, then search is successful(b) If it is less than desired data, then search only the

first half of the array, i.e., the elements which come to the left side of the middle element

(c) If it is greater than the desired data, then search only the second half of the array, i.e., the elements which come to the right side of the middle element

Repeat the same steps until an element is found or exhaust the search area

20

Page 21: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Algorithm for Binary SearchLet A be an array of n elements

A[1],A[2],A[3],...... A[n]“Data” is an element to be searched“mid” denotes the middle location of a

segment (or array or sub-array) of the element of A

LB and UB is the lower and upper bound of the array which is under consideration

21

Page 22: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

1. Input an array A of n elements and “data” to be searched

2. LB = 0, UB = n; mid = int ((LB+UB)/2)3. Repeat step 4,5 and 6 while (LB <= UB) and (A[mid] ! =

data)4. If (data < A[mid])(a) UB = mid–15. Else(a) LB = mid + 16. Mid = int ((LB + UB)/2)7. If (A[mid]== data)(a) Display “the data found”8. Else(a) Display “the data is not found”9. Exit

22

Page 23: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

How a Binary Search Works

Always look at the center value. Each time you get to discard half of the remaining list.

Is this fast ?

23

Page 24: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

How Fast is a Binary Search?Worst case: 11 items in the list

took 4 triesHow about the worst case for a list

with 32 items ?1st try - list has 16 items2nd try - list has 8 items3rd try - list has 4 items4th try - list has 2 items5th try - list has 1 item

24

Page 25: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

How Fast is a Binary Search? (con’t)

List has 250 items

1st try - 125 items 2nd try - 63 items 3rd try - 32 items 4th try - 16 items 5th try - 8 items 6th try - 4 items 7th try - 2 items 8th try - 1 item

List has 512 items

1st try - 256 items 2nd try - 128 items 3rd try - 64 items 4th try - 32 items 5th try - 16 items 6th try - 8 items 7th try - 4 items 8th try - 2 items 9th try - 1 item

25

Page 26: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

What’s the Pattern? List of 11 took 4 triesList of 32 took 5 triesList of 250 took 8 triesList of 512 took 9 tries

32 = 25 and 512 = 29

26

Page 27: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

A Very Fast Algorithm!How long (worst case) will it take

to find an item in a list 30,000 items?

210 = 1024 213 = 8192211 = 2048 214 = 16384212 = 4096 215 = 32768

So, it will take only 15 tries!

27

Page 28: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

log2 n EfficiencyAfter 1 bisectionN/2 itemsAfter 2 bisections N/4 = N/22 items . . .After i bisections N/2i =1 item

i = log2 N

28

Page 29: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Lg n EfficiencyWe say that the binary search algorithm

runs in log2 n time. (Also written as lg n)

Lg n means the log to the base 2 of some value of n.

8 = 23 lg 8 = 3 16 = 24 lg 16 = 4There are no algorithms that run faster

than lg n time.

29

Page 30: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

ExampleSuppose we have an array of 7 elements

Following steps are generated if we binary search a data = 45 from the above array

Step 1:

LB = 0; UB = 6mid = (0 + 6)/2 = 3A[mid] = A[3] = 30

30

Page 31: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Step 2:Since (A[3] < data) - i.e., 30 < 45 -

reinitialise the variable LB, UB and mid

LB = mid+1LB = 4 UB = 6mid = (4 + 6)/2 = 5A[mid] = A[5] = 45

31

Page 32: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Step 3:Since (A[5] == data) - i.e., 45 == 45 -

searching is successful

32

Page 33: Review 1 Arrays & Strings Array Array Elements Accessing array elements Declaring an array Initializing an array Two-dimensional Array Array of Structure

Summary

Introduction to SearchingExternal and Internal SearchingTypes of Searching

Linear or sequential searchBinary Search

Algorithms for Linear SearchAlgorithms for Binary Search

33