Applied Arrays Lists and Strings

34
1 Applied Arrays Lists and Strings Chapter 12

description

Applied Arrays Lists and Strings. Chapter 12. Searching through arrays efficiently. Sorting arrays. Using character arrays as "STRINGS". Applying What You Learn. strings … get it? hahahaha. Lists. Defn => A collection of homogeneous components linear collection - PowerPoint PPT Presentation

Transcript of Applied Arrays Lists and Strings

Page 1: Applied Arrays Lists and Strings

1

Applied ArraysLists and Strings

Chapter 12

Page 2: Applied Arrays Lists and Strings

2

Applying What You Learn

Searching through arrays efficiently

Sorting arrays

Using character arrays as "STRINGS"

strings … get it? hahahaha

Page 3: Applied Arrays Lists and Strings

3

Lists• Defn => A collection of homogeneous

components– linear collection– variable length collection

• Length <=> the actual number of values stored in the list

• Example -- a file of time card information

Joe, 40, Clyde, 38.5, Sniudly, 42.75 ...

Page 4: Applied Arrays Lists and Strings

4

Lists• Arrays can be used to implement a list

– declare the array large– keep track of how many elements used

• We often do operations on the lists– create a list, add an item, delete an item– print the list, search the list for a value– sort the list

• A list of numbersscores : 85 79 92 57 68 80 . . .

0 1 2 3 4 5 98 99

Page 5: Applied Arrays Lists and Strings

5

Sequential Search• Consider the list unordered (not sorted)• For a function to search for a targert we must specify

– name of the array to be searched– length of the list (number of array elements)– a flag parameter which tells whether or

not the search was successful– an index value to be returned which tells where in the list

the item was found

scores

scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

5

boolean & found

int & location

Page 6: Applied Arrays Lists and Strings

6

Sequential Search• Algorithm example

• Note use of reference parameters for the found flag and the location

void search (int list[ ], int length, int target, boolean & found, int &location) { location = 0; while ((location < length) && (target != list[location])) location++; found = (index < length); } // if found == TRUE, location OK . . . search (scores, 5, 92, found_it, where_its_at);

scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99

Page 7: Applied Arrays Lists and Strings

7

Sorted List -- Faster Search

• Sorted list => components arranged in order– alphabetical– numerically ascending or descending

• Advantage of a sorted list– need to search only until the value found is larger

than target value

Page 8: Applied Arrays Lists and Strings

8

Sorting

• Means arranging the list elements into some order (for instance, strings into alphabetical order, or numbers into ascending or descending order).

Dale NellWeems ChipHeadington MarkCooper SoniaHuang Jeff

Cooper Sonia Dale NellHeadington MarkHuang Jeff Weems Chip

sorting

Page 9: Applied Arrays Lists and Strings

9

Sorting Algorithm

• Make a pass through the list, look for smallest number

list 1 : 85 79 92 57 68 80 . . .

list 2 :

Page 10: Applied Arrays Lists and Strings

10

Sorting Algorithm

• Make a pass through the list, look for smallest number

• Write that number in another column, cross it off first list

list 1 : 85 79 92 57 68 80 . . .

list 2 : 57

Page 11: Applied Arrays Lists and Strings

11

Sorting Algorithm

• Make a pass through the list, look for smallest number

• Write that number in another column, cross it off first list

• Repeat process, always look for smallest number remaining

list 1 : 85 79 92 57 68 80 . . .

list 2 : 57 68

Page 12: Applied Arrays Lists and Strings

12

Sorting Algorithm

• Make a pass through the list, look for smallest number

• Write that number in another column, cross it off first list

• Repeat process, always look for smallest number remaining

• Stop when all numbers have been crossed off

Page 13: Applied Arrays Lists and Strings

13

Selection Sort AlgorithmFOR pass going from 0 through length - 2 Find minimum value in list [ pass . . length-1 ] Swap minimum value with list [ pass ]

length = 5

names [ 0 ] Dale Nell Cooper Sonia names [ 1 ] Weems Chip Weems Chip names [ 2 ] Headington Mark Headington Mark names [ 3 ] Cooper Sonia Dale Nell names [ 4 ] Huang Jeff Huang Jeff

pass = 0

Page 14: Applied Arrays Lists and Strings

void SelSort ( /* inout */ String20 names [ ] , /* in */ int length )

// Selection sorts names into alphabetic order// Preconditions: length <= MAX_PERSONS// && names [0 . . length -1 ] are assigned// Postcondition: names [ 0 . . length -1 ] are rearranged into order{ int pass; int place; int minIndex; String20 temp; for ( pass = 0 ; pass < length - 1 ; pass++ ) { minIndex = pass; for ( place = pass + 1 ; place < length ; place ++ ) if ( strcmp ( names [ place ] , names [ minIndex ] ) < 0 )

minIndex = place; //swap names[pass] with names[minIndex]

strcpy ( temp , names [ minIndex ] ) ; strcpy ( names [ minIndex ] , names [ pass] ) ; strcpy ( names [ pass ] , temp ) ; }}

Selection SortAlgorithm

Page 15: Applied Arrays Lists and Strings

15

Sequential Search in a Sorted List

• Note difference from previous search

void search_ord ( int list[ ], int target, int length, int & index, boolean & found)

{ index = 0;list [length] = target; // store an item beyond end while (target > list [index])

index++;found = (index < length && ltem = = list[index]; )

Explain how the last statement works

Page 16: Applied Arrays Lists and Strings

16

Inserting into an Ordered List

• We wish to insert a new number into the list in the right position– find where it goes -- look until you find a number

bigger than the new number

list 2 : 14 22 45 61 87

length : 5

59

Page 17: Applied Arrays Lists and Strings

17

list 2 : 14 22 45 61 87

Inserting into an Ordered List

• We wish to insert a new number into the list in the right position– find where it goes -- look until you find a number

bigger than the new number– shift that number all the rest of the elements down

list 2 : 14 22 45 61 87

length : 5

59

Page 18: Applied Arrays Lists and Strings

18

list 2 : 14 22 45 61 87

Inserting into an Ordered List

• We wish to insert a new number into the list in the right position– find where it goes -- look until you find a number

bigger than the new number– shift that number all the rest of the elements down– insert the new number in the vacated spot

list 2 : 14 22 45 59 61 87

length : 5

59

Page 19: Applied Arrays Lists and Strings

19

length : 5

Inserting into an Ordered List

• We wish to insert a new number into the list in the right position– find where it goes -- look until you find a number

bigger than the new number– shift that number all the rest of the elements down– insert the new number in the vacated spot– be sure to increment the length

length : 6

list 2 : 14 22 45 59 61 87

Page 20: Applied Arrays Lists and Strings

20

Binary Search in an Ordered List• Examines the element in the middle of the array. Is it

the sought item? If so, stop searching. Is the middle element too small? Then start looking in second half of array. Is the middle element too large? Then begin looking in first half of the array.

• Repeat the process in the half of the list that should be examined next.

• Stop when item is found, or when there is nowhere else to look and it has not been located.

Page 21: Applied Arrays Lists and Strings

21

Working with Character Strings

• String => a collection of characters interpreted as a single item– a structured data item– in C++ a null-terminated sequence of characters

stored in a char array• All strings in C++ are terminated by the null

character– character 0,

‘\0’

Page 22: Applied Arrays Lists and Strings

22

Initializing Strings

• When a character array is declared, it is legal to use the assignment operator to initialize

• Note : use of the = operator only legal for char array initialization

• But : aggregate array assignment is NOT

greeting = “don’t do it;

Page 23: Applied Arrays Lists and Strings

23

String Output

• Strings (character arrays) are handled differently than other types of arrays

• This would NOT be allowed

• This is legal:

int num_list [100];. . .cout << num_list;

char name [30] = “Snidly Q. Fizbane”; . . .

cout << name;

Page 24: Applied Arrays Lists and Strings

24

String Input

• Declare strings 1 element bigger than planned size to allow for ‘\0’

• When input takes place, C++ automatically places the ‘\0’ in memory at the end of the characters typed in

Page 25: Applied Arrays Lists and Strings

25

Problems with >> for String Input

• Cannot be used to input a string with imbedded blanks

• >> stops reading as soon as it encounters first whitespace character

Page 26: Applied Arrays Lists and Strings

26

Problems with >> for String Input

• Solve problem by using getline ( … )

Quits reading after 15 charactersor when it hits a newline,

whichever comes first.

Includes all charactersincluding spaces, tabs, etc(whitespace characters)

Page 27: Applied Arrays Lists and Strings

27

Problems with >> for String Input

• If declared string is too small >> keeps putting characters in memory PAST that area in memory

s2 contents extendinto the memory

area of s3

Page 28: Applied Arrays Lists and Strings

28

Using Strings

• Instead of “hard coding” file name for the open ( … ) command, – use a string variable, – use keyboard entry with cin.getline(…)– program more flexible, good for different files

ifstream inFile;char fname[31];cout << “Enter file name -> “;cin.getline (fname, 30, ‘\n’);inFile.open (fname);

Page 29: Applied Arrays Lists and Strings

29

String Library Routines• Recall that we could not use the aggregate

assignment of one string to another• C++ provides some string handling functions

to do this (and other similar tasks)• Found in

<string.h>

Page 30: Applied Arrays Lists and Strings

30

String Library Routines

String comparison:returns -1 if s1 < s2

returns 0 if they are equalreturns +1 if s1 > s2

• String assignment

Returns length of the string

Page 31: Applied Arrays Lists and Strings

31

Using typedef with Arrays

• Specify an array type– this can be used throughout program– helps program self document

• Example :

typedef char default_string [80]; . . .

defalt_string fname, descrip;void reverse (default_string s);

Page 32: Applied Arrays Lists and Strings

32

Testing and Debugging

• Be sure to account for null character when you manipulate characters individually in a string

• Remember proper use of the = – correct for initialization at declarationtime– INCORRECT for aggregate assignment

• Aggregate input/output allowed for strings but NOT for other array types

Page 33: Applied Arrays Lists and Strings

33

Testing and Debugging• If you use the >> for string input, make sure

– string is declared large enough– string will have no white spaces

• The >> operator stops at, but does not consume the first trailing white space– such as ‘\n’ or a space

• The cin.getline (whatever, 30, ‘\n’ ) function – stops when reading the ‘\n’– consumes the ‘\n’– has problems when ‘\n’ is still in the input stream

Page 34: Applied Arrays Lists and Strings

34

Testing and Debugging

• When using the strcpy ( ), make sure that the destination array is declared long enough

• Choose test data carefully for string handling programs– include strings that are too large– include strings with whitespace