340 likes | 451 Views
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
E N D
Applied ArraysLists 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 • 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 ...
scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 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 numbers
scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 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 5 boolean & found int & location
scores : 85 79 92 57 68 80 . . . 0 1 2 3 4 5 98 99 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);
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
Sorting • Means arranging the list elements into some order (for instance, strings into alphabetical order, or numbers into ascending or descending order). Dale Nell Weems Chip Headington Mark Cooper Sonia Huang Jeff Cooper Sonia Dale Nell Headington Mark Huang Jeff Weems Chip sorting
list 1 : 85 79 92 57 68 80 . . . list 2 : Sorting Algorithm • Make a pass through the list, look for smallest number
list 1 : 85 79 92 57 68 80 . . . list 2 : 57 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 68 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
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
Selection Sort Algorithm FOR 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
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
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
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 59 length : 5
list 2 : 14 22 45 61 87 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 59 length : 5
list 2 : 14 22 45 61 87 list 2 : 14 22 45 59 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 59 length : 5
list 2 : 14 22 45 59 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 • be sure to increment the length length : 5 length : 6
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.
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’
greeting = “don’t do it; 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
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;
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
Problems with >> for String Input • Cannot be used to input a string with imbedded blanks • >> stops reading as soon as it encounters first whitespacecharacter
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)
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
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);
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>
String Library Routines • String assignment String comparison:returns -1 if s1 < s2returns 0 if they are equalreturns +1 if s1 > s2 Returns length of the string
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);
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
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
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