19
One Dimensional Arrays (Part2) • Sorting Algorithms • Searching Algorithms • Character Strings • The string Class. 1

One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1

Embed Size (px)

Citation preview

One Dimensional Arrays (Part2)

• Sorting Algorithms

• Searching Algorithms

• Character Strings

• The string Class.

1

2

Sorting Algorithms

• Sorting algorithms arrange the data into either ascending or descending order, based on the values in the array.

• Sorting algorithms: Selection sort

3

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.

4

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]

29 45 18 51 36

18 45 29 51 36swap min and arr[0]

18 29 45 51 3618 29 36 51 45

18 29 36 45 51

#include <iostream>using namespace std;

void display(int list[],int size);void sort(int list[],int size);

int main(){ int list[ ]={5,3,12,8,1,9}; int n=6;

cout<<"List before sorting: "<<endl; display(list, n);

sort(list, n); cout<<"List after sorting: "<<endl; display(list, n); return 0;}//main

//Display listvoid display(int list[],int size){ for(int i=0;i<size;i++)

cout<<list[i]<<" "; cout<<endl;}//display

//Sort the list void sort(int list[],int size){ int min,hold; for(int i=0;i<size-1;i++){ //find the index "min" for the element //with lowest value min=i; for(int k=i+1;k<size;k++)

if(list[min]>list[k]) min= k;

//Exachage list[min] with list[i] hold = list[min]; list[min] = list[i]; list[i] = hold; //Display sorting steps – to be removed cout<<"List in sort fun: i="<<i<<endl; display(list, size); }//for}//sort

5

int list[]={5,3,12,8,1,9}; int list[]={29,45,18,51,36};

6

7

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.

//Search function returns position if element found#include <iostream>using namespace std;

int search(int value, int list[], int size);int main( ){ int list[6]={5,3,12,8,1,9}; int element, index;

cout<<"Enter an element"<<endl; cin>>element;

index= search(element,list,6);

if(index != -1) cout<<"Element "<<element<<" is in index "<<index<<endl; else cout<<"Element " <<element <<" is not in the list "<<endl; return 0;}

int search(int value, int list[], int size){ for (int i=0;i<size;i++) if(value==list[i]) return i; //value is found in list at position i return -1; //value was not found in the list}

8

//search function using returns true if element was found otherwise returns false#include <iostream>using namespace std;bool search(int value, int list[], int size, int& pos);

int main( ){ int list[6]={5,3,12,8,1,9}; int element, index (-1);

cout<<"Enter an element"<<endl; cin>>element; if(search(element,list,6, index))

cout<<"Element "<<element<<" is in index "<<index<<endl; else cout<<"Element " <<element <<" is not in the list "<<endl;

return 0;}//mainbool search(int value, int list[], int size, int& pos){

bool found=false; for (int i=0;i<size && !found;i++)

if(value==list[i]){found=true;pos=i; //value is found in list at position i

} return found;}//search

9

10

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".

11

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 istream class

#include<iostream>#include<fstream>using namespace std;int main(){ char line[100]; ifstream fin; fin.open("xp.txt"); if(fin.fail()){ cout<<"Error opening file xp.txt"<<endl; return 1; } while (fin) { fin.getline(line,100); cout<<line<<endl; }//while return 0;}//main

12

C STYLE STRINGS• In C++, we can define C-Style strings as array of

characters.• C-Style string represents a string as an array of

character ending with the null character ‘\0’ that indicates the end of the string elements.

• Examples • C++: String std=“Ahmed”, col=“Engineering”;• C-Style string: Examples

char std[]={‘A’,’h’,’m’,’e’,’d’,’\0’};

char col[]={‘E’,’n’,’g’,’i’,’n’,’e’,’e’,’r’,’i’,’n’,’g’,’\0’};• ‘\0’ is the null character and occupies one element of

the array but not counted in the size of the array. • ‘\0’ denotes the end of the array elements. 13

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(str): returns the length of the string str

– strcpy(str1,str2): copies two strings str2 into str1

– strcat(str1,str2): appends a copy of str2 to the end of str1

– strcmp(): Compare two strings str1 and str2

14

15

Example: C Style Strings#include <iostream>#include <cstring> //strcmp(), strcpy(), strcat()uses namespace std;int main(){

char str1[30] = “Salim", str2[30] = “Ali";char phrase[20] = "'s shirt was green", sentence[30];if (strcmp (str1,str2) < 0) strcpy (sentence, str1); // puts “Salim" into sentenceelse strcpy (sentence,str2); // puts “Ali” into sentencestrcat (sentence, phrase); //add phrase to sentencecout << "Sentence is: " << sentence << endl;return 0;

}

16

The string class

• Functions defined in String class, i.e. #include <string>

• 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 string class.

String Class• include <string> • declaring string objects

string word="Engineering";

string word2;

• string member functions– size( ) : returns string length– empty( ): checks if the string is empty (true/false)– substr (int start, int len): returns a substring from the specified string– c_str(): converts string format to c string (array of chars)

17

String class operators• relational operators < > == <= >=

• concatenation + +=

• assignment =

18

Example Using string Class#include <iostream>#include <string>using namespace std;int main(){ string str1="Salem", str2=“Ali";

string phrase = "'s shirt was green", sentence;if (str1 < str2) sentence = str1; // puts “Salem" into sentenceelse sentence = str2; // puts “Ali” into sentencesentence += phrase;cout << "Sentence is: " << sentence << endl;return 0;

}Sentence is: Ali's shirt was green

19