310 likes | 324 Views
Learn about one-dimensional arrays, sorting algorithms, and search algorithms in C++ programming. Understand array initialization, access, functions, and practical examples for problem-solving.
E N D
Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays Engineering Problem Solving with C++, Second Edition, J. Ingber
One Dimensional Arrays • Arrays • Sorting Algorithms • Searching Algorithms • Character Strings • The string Class. Engineering Problem Solving with C++, Second Edition, J. Ingber
Definition and Initialization Computation and Output Function Arguments Arrays Engineering Problem Solving with C++, Second Edition, J. Ingber
Definition • An array is a data structure for storing a contiguous block of data. • All data elements in an array must be of the same type. • Individual elements of the array are specified using the array name and an offset. • In C++ the offset of the first element is always 0. Engineering Problem Solving with C++, Second Edition, J. Ingber
? ? ? ? ? ? ? ? Definition and Initialization • Syntax: data_type identifier[size] [= initialization list]; Note: size is an integer constant. • Example: double m[8]; m[0] m[1] m[2] m[3] m[4] m[5] m[6] m[7] Engineering Problem Solving with C++, Second Edition, J. Ingber
'a' 'e' 'i' 'o' 'u' Initializing Arrays • Initializing array elements (initialization=>declaration) char vowels[5] = {'a', 'e', 'i', 'o', 'u'}; bool ansKey[] ={true, true, false, true, false, false}; char word[] = "Hello"; vowels ansKey true true false true false false word 'H' 'e' 'l' 'l' 'o' '\0' Engineering Problem Solving with C++, Second Edition, J. Ingber
Accessing Array Elements • Offsets are used to access individual elements of an array. • General format: array_identifier[offset] • Example for (int i=0; i<=7; ++i) m[i] = double(i) + 0.5; • Integer expressions may be used as offsets. Engineering Problem Solving with C++, Second Edition, J. Ingber
Functions and arrays • An array identifier, without subscripts, references the starting address(first element) of the array. • In C++, arrays are passed by reference. ie the starting address is passed, no size information. • Arrays in C++ to not know their size. • Generally we specify an additional parameter representing the number of elements in the array. Engineering Problem Solving with C++, Second Edition, J. Ingber
Example #include <iostream> using namespace std; const int MAXSIZE=20; void ReadArr(double a[], int& count, istream& in); int FindMin(const double a[], int count); int main( ) { double darr[MAXSIZE]; int cnt=0, position=0; ReadArr(darr, cnt, cin); position = FindMin(darr, cnt); cout << "The smallest value in the array is " << darr[position] << endl; } Engineering Problem Solving with C++, Second Edition, J. Ingber
// This function inputs values into an array until EOF or array // limit reached void ReadArray(double a[], int& count, istream& in) { double temp; count = 0; in >> temp; while ( (count < MAXSIZE) && !in.eof() ) { a[count] = temp; ++count; in >> temp; } } Engineering Problem Solving with C++, Second Edition, J. Ingber
//This function returns the offset of the smallest //value in an array int FindMin(const double a[], int size) { int offsetOfMin = 0; for (int i=1; i<size; ++i) { if (a[i] < a[offsetOfMin] ) { offsetOfMin = i; }//end if }//end for return offsetOfMin; }//end FindMin Engineering Problem Solving with C++, Second Edition, J. Ingber
selection sort Sorting Algorithms Engineering Problem Solving with C++, Second Edition, J. Ingber
Sorting Algorithms • Sorting algorithms arrange the data into either ascending or descending order, based on the values in the array. • Sorting algorithms to be discussed • Selection sort Engineering Problem Solving with C++, Second Edition, J. Ingber
Selection Sort Algorithm • Find minimum value, place it in the first position. • Find next minimum value, place it in the second position. • Continue doing this until you have placed the second to the largest value in the second to the last position. Engineering Problem Solving with C++, Second Edition, J. Ingber
Practice! • Fill in the following table to show how the array is sorted into ascending order using the selection sort. arr[0] arr[1] arr[2] arr[3] arr[4] swap min and arr[0] 18 2945 51 36 18 29 36 51 45 18 29 36 4551 Engineering Problem Solving with C++, Second Edition, J. Ingber
unordered lists ordered lists Search Algorithms Engineering Problem Solving with C++, Second Edition, J. Ingber
Searching Unordered Lists • Simple Sequential Search • Examine each element starting with the first one until: • a match is found. • end of the list is reached. • Sequential search can be implemented as: • a function which returns true if item in the list, false if item is not in the list. • a function which returns the location of the item if found, or –1 if not found. Engineering Problem Solving with C++, Second Edition, J. Ingber
Searching Ordered Lists • Modified Sequential Search: • examine every element in the list until: • item is found. • list element is larger/smaller than the item you are searching for (search fails). • Binary Search • Examine middle element: • if element equals item, item found, return location. • if element is larger than item ignore bottom of list. • if element is smaller than item ignore top of list. • Repeat until: • item is found. • top and bottom cross over (search failed). Engineering Problem Solving with C++, Second Edition, J. Ingber
37 43 Example of Binary Search for 48 5 11 14 22 28 37 43 56 59 70 arr[top] arr[mid] arr[bot] 37 43 56 59 70 mid is 7 arr[top] arr[mid] arr[bot] mid is 5 arr[top] arr[bot] mid is 6 43 arr[6] 43 arr[bot] arr[top] Engineering Problem Solving with C++, Second Edition, J. Ingber
C style strings functions defined in cstring Character Strings Engineering Problem Solving with C++, Second Edition, J. Ingber
C Style Character Strings • A C style strings is defined as a sequence of characters, terminated by the null character. • When declaring a character array to store a C style string, memory must be allocated for the null character ('\0'). • Literal string constants are enclosed within double quote marks: "a string". Engineering Problem Solving with C++, Second Edition, J. Ingber
C Style String Input • Recall that the input operator (>>) skips whitespace . • To input strings with embedded whitespace , the getline() function can be used as illustrated: char phrase[SIZE]; cin.getline(phrase, SIZE); • The getline() function reads up to SIZE-1 characters from the input stream and will insert the null character. • getline() is a member function of what class? Engineering Problem Solving with C++, Second Edition, J. Ingber
C STYLE STRING FUNCTIONS • The Standard C++ library contains a set of predefined functions that operate on C style strings. • These functions are defined in the header file: cstring • Commonly used string functions: • strlen() • strcpy() • strcat() • strcmp() Engineering Problem Solving with C++, Second Edition, J. Ingber
Example: C Style Strings #include <iostream> #include <cstring> //strcmp(), strcpy(), strcat() uses namespace std; int main(){ char str1[30] = "John", str2[30] = "Johnson"; char phrase[20] = "'s shirt was green", sentence[30]; if (strcmp(str1,str2) < 0) strcpy (sentence, str1); // puts "John" into sentence else strcpy (sentence,str2); // puts "Johnson into sentence strcat(sentence, phrase); cout << "Sentence is: " << sentence << endl; return 0; } Engineering Problem Solving with C++, Second Edition, J. Ingber
functions defined in string The string class Engineering Problem Solving with C++, Second Edition, J. Ingber
The string class • The string class implements the concept of a character string. • A string object can increase and decrease its size dynamically. • Numerous operators and functions are defined in the stringclass. Engineering Problem Solving with C++, Second Edition, J. Ingber
Common Functions Defined in string • size( ) • empty( ) • substr (int start, int len) • c_str() Engineering Problem Solving with C++, Second Edition, J. Ingber
Overloaded Operators Defined in string • relational operators • < > == <= >= • concatenation • + += • assignment • = Engineering Problem Solving with C++, Second Edition, J. Ingber
Example: string class #include <iostream> #include <string> uses namespace std; int main(){ string str1 = "John", str2 = "Johnson"; string phrase = "'s shirt was green", sentence; if (str1 < str2) sentence = str1; // assign "John" to sentence else sentence = str2; // assign "Johnson to sentence sentence += phrase; // append phrase to sentence cout << "Sentence is: " << sentence << endl; return 0; } Engineering Problem Solving with C++, Second Edition, J. Ingber