CHAPTER 10 ARRAYS II Applications and Extensions.

Slides:



Advertisements
Similar presentations
TK1914: C++ Programming Array II. Objective In this chapter you will explore how to manipulate data in a two-dimensional array. 2FTSM :: TK1914,
Advertisements

Java Programming: From Problem Analysis to Program Design, 3e Chapter 10 Applications of Arrays.
Searching Algorithms. Lecture Objectives Learn how to implement the sequential search algorithm Learn how to implement the binary search algorithm To.
1 Lecture 21:Arrays and Strings(cont.) Introduction to Computer Science Spring 2006.
1 Lecture 25:Pointers Introduction to Computer Science Spring 2006.
Data Structures Using Java1 Chapter 8 Search Algorithms.
1 Lecture 23:Applications of Arrays Introduction to Computer Science Spring 2006.
1 Lecture 20:Arrays and Strings Introduction to Computer Science Spring 2006.
Objectives Learn how to implement the sequential search algorithm Explore how to sort an array using the selection sort algorithm Learn how to implement.
Chapter 9: Arrays and Strings
Chapter 9: Arrays and Strings
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Chapter 9: Arrays and Strings
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Arrays. Objectives Learn about arrays Explore how to declare and manipulate data into arrays Learn about “array index out of bounds” Become familiar with.
Arrays (Part II). Two- and Multidimensional Arrays Two-dimensional array: collection of a fixed number of components (of the same type) arranged in two.
1 Lecture 22:Applications of Arrays Introduction to Computer Science Spring 2006.
Prepared by MURLI MANOHAR PGT (COMPUTER SCIENCE) KV,B.E.G., PUNE.
1 Introduction to Arrays Problem: –Input 5 scores, compute total, average –Input Example –test scores,employees,temperatures.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
Data Structures Using Java1 Chapter 8 Search Algorithms.
Arrays Multi-dimensional initialize & display Sample programs Sorting Searching Part II.
Chapter 16: Searching, Sorting, and the vector Type.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
Data Structures Using C++1 Chapter 9 Search Algorithms.
Data Structures and Algorithms.
Chapter 8 Arrays and Strings
Applications of Arrays (Searching and Sorting) and Strings
Lecture 12. Searching Algorithms and its analysis 1.
Data Structures & Algorithms CHAPTER 4 Searching Ms. Manal Al-Asmari.
1 DATA STRUCTURES: LISTS. 2 LISTS ARE USED TO WORK WITH A GROUP OF VALUES IN AN ORGANIZED MANNER. A SERIES OF MEMORY LOCATIONS CAN BE DIRECTLY REFERENCED.
EGR 2261 Unit 8 One-dimensional Arrays  Read Malik, pages in Chapter 8.  Homework #8 and Lab #8 due next week.  Quiz next week.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Java Programming: From Problem Analysis to Program Design, 4e
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition Second Edition.
C++ Programming: From Problem Analysis to Program Design, Fifth Edition Arrays.
Lecture 7 Introduction to Programming in C Arne Kutzner Hanyang University / Seoul Korea.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Chapter 14: Searching and Sorting
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 10: Applications of Arrays (Searching and Sorting) and the vector Type.
1 Topic: Array Topic: Array. 2 Arrays Arrays In this chapter, we will : Learn about arrays Learn about arrays Explore how to declare and manipulate data.
Week # 2: Arrays.  Data structure  A particular way of storing and organising data in a computer so that it can be used efficiently  Types of data.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
1 Arrays and Strings Lecture: Design Problem l Consider a program to calculate class average Why?? ?
Data Structures Using C++
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Chapter 10: Class Vector and String, and Enumeration Types Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
CHAPTER 10 ARRAYS II Applications and Extensions.
1 Chapter 9 Arrays Java Programming from Thomson Course Tech, adopted by kcluk.
Java Programming: Chapter 9: Arrays
Opening Input/Output Files ifstream infile; ofstream outfile; char inFileName[40]; char outFileName[40]; coutinFileName;
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
1 Chapter 9 Arrays Java Programming from Thomson Course Tech, adopted by kcluk.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
Chapter 9 Arrays. Chapter Objectives Learn about arrays Explore how to declare and manipulate data into arrays Understand the meaning of “array index.
Chapter 16: Searching, Sorting, and the vector Type.
1 Why do we need arrays? Problem - Input 5 test scores => int test1,test2,test3,test4,test5 100 test scores? 10,000 employees? A structured data type is.
1 Arrays and Variable Length Parameter List  The syntax to declare a variable length formal parameter (list) is: dataType... identifier.
Chapter 9: Arrays J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
Chapter 16: Searching, Sorting, and the vector Type
EGR 2261 Unit 10 Two-dimensional Arrays
Chapter 8: Arrays Starting Out with C++ Early Objects Ninth Edition
Computer Programming BCT 1113
Basic Array Definition
Arrays … The Sequel Applications and Extensions
Lecture 9 Objectives Learn about arrays.
Presentation transcript:

CHAPTER 10 ARRAYS II Applications and Extensions

In this chapter, you will:  Learn how to implement the sequential search algorithm  Explore how to sort an array using the selection sort algorithm  Learn how to implement the binary search algorithm  Discover how to manipulate data in a two-dimensional array  Learn about multidimensional arrays

LIST PROCESSING  A list is defined as a set of values of the same type.  Some of the basic operations that are performed on a list are: 1. Search the list for a given item. 2. Sort the list. 3. Insert an item in the list. 4. Delete an item from the list.

Sequential Search found is set to false; for(loc = 0; loc < length; loc++) if(list[loc] is equal to searchItem) { found is set to true exit loop } if(found) return loc; else return –1; If the function seqSearch returns a value greater than or equal to 0, it is a successful search; otherwise, it is an unsuccessful search.

int seqSearch(const int list[], int listLength, int searchItem) { int loc; bool found = false; for(loc = 0; loc < listLength; loc++) if(list[loc] == searchItem) { found = true; break; } if(found) return loc; else return -1; }

Sorting a List: Selection Sort This algorithm a. Finds the location of the smallest element b. Move the smallest element to the beginning of the unsorted list. for(index = 0; index < length – 1; index++) { a. Find the location, smallestIndex, of the smallest element in list[index]...list[length]. b. Swap the smallest element with list[index]. That is, swap list[smallestIndex] with list[index]. }

Step a: smallestIndex = index; //assume first element is the //smallest for(minIndex = index + 1; minIndex < length; minIndex++) if(list[minIndex] < list[smallestIndex]) smallestIndex = minIndex; //current element in //the list is smaller than //the smallest so far, so //update smallestIndex Step b: temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp;

Before writing the selection sort function, let us apply the above algorithm to sort the following list. The length of list is 6

Iteration 1: Sort list[0]...list[5]. Step a: Find the index of the smallest element in list[0]...list[5]. Step b: Swap list[smallestIndex] with list[index], that is, list[3] with list[0]. The resulting array is:

Iteration 2: Sort list[1]...list[5]. Here index = 1. Step a: Find the index of the smallest element in list[1]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[1] with list[1].

Iteration 3: Sort list[2]...list[5]. Step a: Find the index of the smallest element in list[2]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[4] with list[2].

Iteration 4: Sort list[3]...list[5]. Step a: Find the index of the smallest element in list[3]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[3] with list[3].

Iteration 5: Sort list[4]...list[5]. Step a: Find the index of the smallest element in list[4]...list[5]. Step b: Swap list[smallestIndex] with list[index]. That is, swap list[5] with list[4].

void selectionSort(int list[], int length) { int index; int smallestIndex; int minIndex; int temp; for(index = 0; index < length – 1; index++) { //Step a smallestIndex = index; for(minIndex = index + 1; minIndex < length; minIndex++) if(list[minIndex] < list[smallestIndex]) smallestIndex = minIndex; //Step b temp = list[smallestIndex]; list[smallestIndex] = list[index]; list[index] = temp; }

S equential search on a sorted list found is set to false; for(loc = 0; loc < listLength; loc++) if (list[loc] is greater than or equal to searchItem) { found is set to true exit loop } if(found) if(list[loc] == searchItem) return loc; else return –1; else return –1;

int seqOrderdSearch(const int list[], int listLength, int searchItem) { int loc;//Line 1 bool found = false;//Line 2 for(loc = 0; loc < listLength; loc++)//Line 3 if(list[loc] >= searchItem)//Line 4 { found = true;//Line 5 break;//Line 6 } if(found)//Line 7 if(list[loc] == searchItem)//Line 8 return loc;//Line 9 else//Line 10 return –1;//Line 11 else//Line 12 return –1;//Line 13 }

length = 8 ; searchItem = 35 ; loc = 0, found = false. Iteration locfoundlist[loc]list[loc]>= searchItem 1 0false44 >= 35 is false; loc = 1 2 1false1818 >= 35 is false;loc = 2 3 2false2929 >= 35 is false;loc = 3 4 3false3535 >= 35 is true; found = true  found is true, the if statement at Line 8 executes.  list[loc] = 35 and searchItem = 35, the expression list[loc] == searchItem evaluates to true and the return statement at Line 9 returns the value of loc, which is 3. This is a successful search.

searchItem = 40 ; loc = 0 ; found = false. Iteration locfound list[loc] list[loc]>= searchItem 1 0false44 >= 40 is false; loc = 1 2 1false1818 >= 40 is false; loc = 2 3 2false2929 >= 40 is false; loc = 3 4 3false3535 >= 40 is false; loc = 4 5 4false4444 >= 40 is true; found = true found is true. The if statement at Line 8 executes. list[loc] = 44 and searchItem = 40. The expression list[loc] == searchItem evaluates to false, the statement at Line 9 is skipped, and the return statement at Line 11 executes, which returns –1. This is an unsuccessful search.

Binary Search  A binary search is similar to a dictionary search.  A binary search uses the “divide and conquer” technique to search the list.  First, the search item is compared with the middle element of the list.  If the search item is less than the middle element of the list, we restrict the search to the upper half of the list; otherwise, we search the lower half of the list. Consider the following sorted list of length = 12

Determine whether 75 is in the list Compare 75 with the middle element in the list, list[5] (which is 39 ). Because 75  list[5] and 75 > list[5], we then restrict our search to the list list[6]...list[11]

int binarySearch(const int list[],int listLength,int searchItem) { int first = 0; int last = listLength - 1; int mid; bool found = false; while(first <= last && !found) { mid = (first + last) / 2; if(list[mid] == searchItem) found = true; else if(list[mid] > searchItem) last = mid - 1; else first = mid + 1; } if(found) return mid; else return –1; }//end binarySearch

searchItem = 89 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp ( found is true ) searchItem = 34 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp ( found is true )

searchItem = 22 ; first = 0, last = 11, and found = false Iteration firstlastmidlist[mid] Number of Key Comp The loop stops (because first > last ) unsuccessful search

Two-dimensional Array: A two-dimensional array is a collection of a fixed number of components arranged in two dimensions, and all components are of the same type. The syntax for declaring a two-dimensional array is: dataType arrayName[# of Rows][# of Column]; double sales[10][5]; declares a two-dimensional array sales of 10 rows and 5 columns and every component is of the type float.

Two-Dimensional Array Initialization During Declaration Like one-dimensional arrays, two-dimensional arrays can be initialized when they are declared. int board[4][3] = {{2, 3, 1}, {15, 25, 13}, {20,4,7}, {11,18,14}};

Processing Two-dimensional Arrays const int rows = 7; const int columns = 6; int matrix[rows][columns]; int row; int col; int sum; int largest; int temp;

Initialize the 6th row to zero row = 5; for(col = 0; col < columns; col++) matrix[row][col] = 0;

Print out the 3rd column to screen output col = 2; for(row = 0; row < rows; row++) cout << matrix[row][col] << endl;

Print The following nested for loops print the components of matrix, one row per line. for(row = 0; row < rows; row++) { for(col = 0; col < columns; col++) cout<<setw(5)<<matrix[row][col]<<" "; cout<<endl; }

Sum of each individual row for(row = 0; row < rows; row++) { sum = 0; for(col = 0; col < columns; col++) sum = sum + matrix[row][col]; cout<<"Sum of row "<<row+1<<" = " <<sum<<endl; } Sum of each individual column for(col = 0; col < columns; col++) { sum = 0; for(row = 0; row < rows; row++) sum = sum + matrix[row][col]; cout<<"Sum of column "<<col+1<<" = " <<sum<<endl; }

//Largest element in each row for(row = 0; row < rows; row++) { largest = matrix[row][0]; for(col = 1; col < columns; col++) if(largest < matrix[row][col]) largest = matrix[row][col]; cout<<"Largest element of row "<<row+1 <<" = "<<largest<<endl; }

//Largest element in each column for(col = 0; col < columns; col++) { largest = matrix[0][col]; for(row = 1; row < rows; row++) if(largest < matrix[row][col]) largest = matrix[row][col]; cout<<"Largest element of col "<<col+1 <<" = "<<largest<<endl; }

Passing Two-dimensional Arrays as Parameters to Functions Two-dimensional arrays can be passed as parameters to a function and they are passed by reference. The base address, that is, the address of the first component of the actual parameter is passed to the formal parameter. When storing a two-dimensional array in the computer’s memory, C++ uses the row order form. That is, first the first row is stored, followed by the second row, which is followed by the third row and so on. void example(int table[][5], int rowsize) {. }

Arrays of Strings Arrays of Stings and the string Type string list[100]; Arrays of Strings and C- Strings (Character Arrays) char list[100][16];

strcpy(list[1], "Snow White"); for(j = 0; j < 100; j++) cout<<list[j]<<endl;

Other form of Declaring Two-dimensional Arrays const int numberOfRows = 20; const int numberOfColumns = 10; typedef int tableType[numberOfRows][numberOfColumns]; We can declare variables of the type tableType. tableType matrix; void initialize(tableType table) { int row; int col; for(row = 0; row < numberOfRows; row++) for(col = 0; col < numberOfColumns; col++) table[row][col] = 0; }

Multi-dimensional Arrays Array: An array is a collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1), called an n - dimensional array. The general syntax of declaring an n -dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1, intExp2, …, and intExpn are constant expressions yielding positive integer values. The syntax of accessing a component of an n-dimensional array is: arrayName[indexExp1][indexExp2]...[indexExpn] where indexExp1, indexExp2,..., and indexExpn are expressions yielding nonnegative integer values. indexExpi gives the position of the array component in the ith dimension.

The statement declares carDealers to be a three-dimensional array. double carDealers[10][5][7];  Size of the first dimension is 10 and it ranges from 0 to 9.  The size of the second dimension is 5 and it ranges from 0 to 4.  The size of the third dimension is 7 and it ranges from 0 to 6.  The base address of the array carDealers is the address of the first array component, that is the address of carDealers[0][0][0].  The total number of components in the array carDealers is 10*5*7 = 350. carDealers[5][3][2] = ; for(i = 0; i < 10; i++) for(j = 0; j < 5; j++) for(k = 0; k < 7; k++) carDealers[i][j][k] = 0.0; initializes the entire array to 0.0.