35
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part

Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Embed Size (px)

Citation preview

Page 1: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Arrays

Multi-dimensional initialize & display

Sample programs

Sorting

Searching

Part II

Page 2: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Multidimensional Arrays

a everything about one dimensional arrays applies *

a all elements of the same data type

a just need additional sets of [ ][ ]

a a 3-D array has rows, columns, and rank

* Except leaving the size out of the formal parameter

Page 3: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

A

B

C

D

F

28

40

29

9

14

parallel arrays = two or more arrays in which elements with corresponding indexes are related

We WILL do this in the next lab

Parallel Arrays

Used when related data is of different data types.grade % of class

*

Page 4: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Parallel Arrays

for(row…

for(col…{ cout << “Enter id#”;

cin >> id[row][col];

cout << “Enter grade”;cin >> grade[row][col];

}

OR for(row…

for(col…

{ cout << “Enter id and grade”;

cin >> id[row][col] >> grade[row][col];

}

Page 5: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Sum a Row

void main(void){

double nums [3][4] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12};

double sumRow(double [3] [4]); // prototype

cout << “The sum of row 3 is “ << sumRow(nums)<<endl; //function call

}

Page 6: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Sum a Row

double sumRow(double ary[3][4]){ int col; double total=0;

for(col = 0; col < 4; col++)total += ary[ ][col];

return total;}

* *

total += ary[2][col]; //enter row # -1

output The sum of row 3 is 42The sum of row 3 is 42

Page 7: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Sum a Column

void main(void){

double nums [3][4] = {1, 2, 33, 4, 5, 6, 77, 8, 9, 10, 1111, 12};

double sumCol(double [3] [4]); // prototype

cout << “The sum of column 3 is “ << sumCol(nums) << endl; //function call

}

Page 8: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Sum a Column

double sumCol(double ary[3][4]){ int row; double total=0;

for(row = 0; row<3; row++)total += ary[row][ ];

return total;}

*

total += ary[row][2]; //enter col # -1

output The sum of column 3 is 21The sum of column 3 is 21

Page 9: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review -1

Write a C++ program that adds equivalent elements of the two-dimensional arrays named first and second. Both arrays should have two rows and three columns. For example, element [1][2] of the resulting array should be the sum of first[1][2] and second[1][2].

first second16 18 23 24 52 7754 91 11 16 19 59

sum40 70 10070 110 70

*

Page 10: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Sorting

Internal Sorts [for small data sets]

bubble (exchange)

selection

External Sorts [for large data sets]

Page 11: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Bubble Sort

Put smaller first

Put smaller first

No change

Put smaller first21 252513 9 1717

2121 252513 9 17

99 252121 13 17

9 2513 21 17

Page 12: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Bubble Sort

Begin again and put smaller first

No change

Put smaller first

21 179 13 25

17 21219 13 2525

2121 171313 9 25

2121 17179 13 25

Page 13: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

A Bubble Sort Functionvoid bubble_sort(int array[ ], int length){

int j, k, flag=1, temp;for(j=1; j<=length && flag; j++){

flag=0; // falsefor(k=0; k < (length-j); k++){

if (array[k+1] > array[k]) // > low to high{

temp=array[k+1]; // swaparray[k+1]= array[k];array[k]=temp;flag=1; // indicates a swap

}} }} }} }} // has occurred

Page 14: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Selection Sortindex (k) sm_index

0 2swap 21, 9

1 1swap 13, 13

2 3swap 21, 15

3 4swap 21, 17

21 159 13 17

15 179 13 21

99 152121 13 17

15 21219 13 1717

2121 15159 13 17

Page 15: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Selection Sortvoid sort(double [5]);void swap(double [5], int, int); // prototypesvoid main(void){ int index;

double my_list[ ] = {21, 13, 9, 15, 17};cout << "\nThe unsorted array is: \n";

for(index=0; index<5; index++)cout << “ “ << my_list[index] << endl;

sort(my_list); // function callcout << "\nThe sorted array is: \n";for(index=0; index<5; index++)

cout << “ “ << my_list[index] << endl;}

Page 16: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Selection Sortvoid sort(double testArray[5]){ int n, k, sm_index, pass=0;

double smallest;

for(k=0; k<4; k++) // size-1 = number of passes{ smallest = testArray[k];

sm_index = k;for(n=k+1; n<5; n++) // size = # elem. to look at

if(testArray[n] < smallest){ smallest = testArray[n];

sm_index = n;}

swap(testArray, sm_index, k); // call to swap()}

}

Page 17: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Selection Sort

void swap(double testArray[5], int smaller, int position)

{ // position = current position: kdouble temp;

temp = testArray[position];testArray[position] = testArray[smaller];testArray[smaller] = temp;

}

Page 18: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Linear Search Pseudocode

For all the items in the listCompare the item with the desired itemIf the item was found

Return the index value of the current item(the position of the element in the array)

End IfEnd ForReturn -1 because the item was not found

Page 19: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

The “Classic” Linear Search Function

int LinearSearch(int list[], int size, int key){ // or “Sequential search” int i; for (i = 0; i < size; i++) { if (list[i] = = key) return i; // return location of element

//this will terminate the loop } return -1; // element not in list}

Page 20: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Main for linear searchint main() { int LinearSearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {22,5,67,98,45,32,101,99,73,10}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = LinearSearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; }

Page 21: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Binary Search

List must be in sorted order

The function looks at the midpoint

If the midpoint is the item, return the location

Else, determine if the item is less than or greater than the midpoint

Eliminate the side where the item cannot be, and declare a new midpoint

Go again. (A recursive function)

Half the list is eliminated on each pass

Page 22: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

int BinarySearch(int list[], int size, int key) { int left, right, midpt; // list must be in sorted order left = 0; // left end is the first element right = size - 1; // right is the last element while (left <= right){ midpt = (int) ((left + right) / 2); // why integer division? if (key == list[midpt]) return midpt; // if found, the key will be the midpoint else if (key > list[midpt]) // eliminate the left half left = midpt + 1; else right = midpt - 1; // else - eliminate the right half } // end whilereturn -1;} // the key was never found

Page 23: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Main for binary searchint main() { int BinarySearch(int [], int, int); // prototype const int NUMEL = 10; int nums[NUMEL] = {5,10,22,32,45,67,73,98,99,101}; int item, location; cout << "\nEnter the item you are searching for: "; cin >> item; location = BinarySearch(nums, NUMEL, item); if (location > -1) cout << "The item was found at index location " << location << endl; else cout << "The item was not found in the list\n"; return 0; }

Page 24: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review

a is an ordered sequence of dataof the same type

a can be of any valid data type

a can be 1-, 2-, or multi- dimensional

a must be declared before used

a can be assigned and initialized

a element numbering starts at zero

Page 25: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review

a use for loops to access (nested for multidimentional)

a can be passed back and forth between functions

a when sent to functions the actual values are manipulated - not a copy

(passed by reference)

Page 26: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6a

There is an array of three students each with four exam scores. Assume the scores are known and are: {77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}. Create a program which will display the lowest grade, the highest grade and the average of the grades to two decimal places.

Page 27: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6b

#include <iostream>#include <iomanip.>using namespace std;

const int STUDENTS = 3; // global, so main and allconst int EXAMS = 4; // functions can access

int mini (int [][EXAMS], int, int);

int maxi (int [][EXAMS], int, int);

float average(int [], int);

void printArray(int [][EXAMS], int, int);

Page 28: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6cvoid main(void){ int studentGrades[STUDENTS][EXAMS] =

{{77, 68, 86, 73}, {96, 87, 89, 78}, {70, 90, 86, 81}};

cout << "The array is:" << endl; printArray(studentGrades, STUDENTS, EXAMS); cout<<endl<<endl<<"Lowest grade: " << mini (studentGrades, STUDENTS, EXAMS)

<< endl << "Highest grade: " << maxi (studentGrades, STUDENTS, EXAMS)<<endl;

for (int person = 0; person < STUDENTS; person++) cout << "The average grade for student " << person << " is " <<setiosflags(ios::fixed | ios::showpoint)<<setprecision(2) << average(studentGrades[person], EXAMS) << endl;}

Page 29: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6d

int mini(int grades[][EXAMS], int pupils, int tests)

{ int lowGrade = 100; for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) if (grades[i][j] < lowGrade) lowGrade = grades[i][j]; return lowGrade; }

int maxi(int grades[][EXAMS], int pupils, int tests)

{ int highGrade = 0; for (int i = 0; i < pupils; i++) for (int j = 0; j < tests; j++) if (grades[i][j] > highGrade) highGrade = grades[i][j]; return highGrade; }

Page 30: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6e

float average(int setOfGrades[],int tests)

{ int total = 0; for (int i = 0; i < tests; i++) total += setOfGrades[i]; return (float) total / tests; }

void printArray(int grades[][EXAMS], int pupils, int tests) { cout << " [0] [1] [2] [3]"; for (int i = 0; i < pupils; i++) { cout << endl<< "studentGrades["

<< i << "] ";

for (int j = 0; j < tests; j++) cout << setiosflags(ios::left)

<< setw(5) << grades[i][j]; }

Page 31: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Array Review - 6f

function call:average(studentGrades[person],

EXAMS)

float average(int setOfGrades[], int tests){ int total = 0;

for (int i = 0; i < tests; i++) total += setOfGrades[i];

return total / tests;}

Page 32: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Common Errors

Not declaring the arrayNot declaring the array First element is called First element is called zerozero; last element ; last element

is one less than the number of elementsis one less than the number of elements Out of rangeOut of range subscripts - no warning subscripts - no warning Error in the Error in the forfor loop - check the counter loop - check the counter Not initializing the arrayNot initializing the array

Page 33: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Common Errors

Aggregate operations not allowedAggregate operations not allowed Omitting array size - permitted only Omitting array size - permitted only

when declared as a formal parameter when declared as a formal parameter initialized in the declarationinitialized in the declaration

If array is /* in */ only, declare the If array is /* in */ only, declare the formal parameter as formal parameter as constconst to prevent to prevent accidental modificationaccidental modification

Page 34: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

Debugging

array subscriptsarray subscripts

recheck array size in declaration, recheck array size in declaration, initialization, and initialization, and forfor loops loops

Prevention - plan first!Prevention - plan first!Valuation tablesValuation tablesDisplay values with coutDisplay values with cout

C++ DebuggerC++ Debugger

Page 35: Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II

I really hate this darn machine,I really hate this darn machine,

I wish they would sell it.I wish they would sell it.

It never does quite what I want,It never does quite what I want,

But only what I tell it.But only what I tell it.

End Note