Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Arrays. What is an array An array is used to store a collection of data It is a collection of variables of the same type.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 7- 1 Overview 7.1 Introduction to Arrays 7.2 Arrays in Functions 7.3.
Arrays Chapter 6. Outline Array Basics Arrays in Classes and Methods Sorting Arrays Multidimensional Arrays.
Arrays.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Engineering Problem Solving With C++ An Object Based Approach Chapter 6 One-Dimensional Arrays.
Programming with Collections Collections in Java Using Arrays Week 9.
Arrays. A group of data with same type stored under one variable. It is assumed that elements in that group are ordered in series. In C# language arrays.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
1 Arrays  Arrays are objects that help us organize large amounts of information  Chapter 8 focuses on: array declaration and use passing arrays and array.
Array Must declare a variable to reference the array double [] mylist; // cannot double list[20]; Or double mylist[]; The declaration doesn’t allocate.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
Arrays.
Part 2. Searching Arrays Looking for a specific element in an array E.g., whether a certain score (85) is in a list of scores Linear search Binary search.
One Dimensional Arrays (Part2) Sorting Algorithms Searching Algorithms Character Strings The string Class. 1.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 8: Searching and Sorting Arrays.
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Arrays in C++ UNIVERSITY OF THE PUNJAB (GUJRANWALA CAMPUS) 1 ADNAN BABAR MT14028 CR
C++ Arrays. Agenda What is an array? What is an array? Declaring C++ arrays Declaring C++ arrays Initializing one-dimensional arrays Initializing one-dimensional.
Arrays in C++ Numeric Character. Structured Data Type A structured data type is a type that stores a collection of individual components with one variable.
Lecture DS & Algorithms:09 Abstract Data Types. Lecture DS & Algorithms:09 2 Abstract Data Types Data Type: A data type is a collection of values and.
Chapter 6 One-Dimensional Arrays ELEC 206 Computer Tools for Electrical Engineering.
Chapter 8 Searching and Sorting Arrays Csc 125 Introduction to C++ Fall 2005.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
Chapter Searching and Sorting Arrays 8. Introduction to Search Algorithms 8.1.
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.
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
ARRAYS Computer Engineering Department Java Course Asst. Prof. Dr. Ahmet Sayar Kocaeli University - Fall
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
Pointers OVERVIEW.
Arrays & Vectors Week 5. The simplest form of the multidimensional array is the two-dimensional array. A two- dimensional array is, in essence, a list.
CHAPTER 7 arrays I NTRODUCTION T O C OMPUTER P ROGRAMMING (CSC425)
Dynamic memory allocation and Pointers Lecture 4.
Chapter overview This chapter focuses on Array declaration and use Bounds checking and capacity Arrays storing object references Variable length parameter.
Scope When we create variables and functions, they are limited in where they are visible and where they can be referenced For the most part, the identifiers.
Templates “Generic Programming” ECE Templates A way to write code once that works for many different types of variables –float, int, char, string,
12/15/2015Engineering Problem Solving with C++, Second Edition, J. Ingber 1 Engineering Problem Solving with C++, Etter Chapter 6 One-Dimensional Arrays.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
Chapter 7: Arrays. Outline Array Definition Access Array Array Initialization Array Processing 2D Array.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Arrays.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
Starting Out with C++, 3 rd Edition Introduction to the STL vector The Standard Template Library (or STL) is a collection of data types and algorithms.
COMPUTER PROGRAMMING. Array C++ provides a data structure, the array, which stores a fixed-size sequential collection of elements of the same type. An.
CSE 251 Dr. Charles B. Owen Programming in C1 Intro to Arrays Storing List of Data.
Glenn Stevenson CSIS 113A MSJC CSIS 123A Lecture 3 Vectors.
Data Structures Arrays and Lists Part 2 More List Operations.
1 Arrays: Matrix Renamed Instructor: Mainak Chaudhuri
The Selection Sort Mr. Dave Clausen La Cañada High School.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
SORTING Sorting is storage of data in some order, it can be in ascending or descending order. The term Sorting comes along-with the term Searching. There.
14-1 Computing Fundamentals with C++ Object-Oriented Programming and Design, 2nd Edition Rick Mercer Franklin, Beedle & Associates, 1999 ISBN
Lecture #15 ARRAYS By Shahid Naseem (Lecturer). 2 ARRAYS DEFINITION An array is a sequence of objects of same data type. The objects in an array are also.
Arrays as Function Parameters. CSCE 1062 Outline  Passing an array argument (section 9.3)  Reading part of an array (section 9.4)  Searching and sorting.
1 C++ Data Types structured array struct union class address pointer reference simple integral enum char short int long bool floating float double long.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.
Recitation 13 Searching and Sorting.
Chapter 8 Arrays, Strings and pointers
Write code to prompt for 5 grades, read them in, print “Thank you”, then reprint the 5 grades and their average. cout >
Object Oriented Programming in java
2 code samples int [] array; int i, j, temp; for(i = 0; i < array.length/2; i++) { j = array.length-1-i; temp = array[i]; array[i] = array[j]; array[j]
Engineering Problem Solving with C++, Etter
Arrays Lecture 11.
Arrays in Java.
Intro to Arrays Storing List of Data.
Data Structure(s) A way of storing and organizing data in a computer so that it can be used efficiently. e.g. Arrays Linked Lists stacks Queues Trees.
8.3 Vectors Copyright © 2008 Pearson Addison-Wesley. All rights reserved. 1.
Arrays.
Presentation transcript:

Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003

Searching an Array We used a simple linear search in program 1. while(aTrans.partNum != invArr[i].get_partNum) i++; -or- while(!found) if(aTrans.partNum == invArr[i].get_partNum) found = true; else i++;

A Better Search A linear search in necessary if the array is in no particular order. A better search could be performed if the array were known to be in a specific order. Therefore a sorting function is necessary.

Sorting an Array Numeric arrays can easily be sorted, either lowest to highest (ascending) or highest to lowest (descending). String arrays can also be sorted alphabetically (ascending or descending).

Selection Sort If we are sorting the array in ascending order, we find the smallest element and place that in index 0, then the next smallest is placed in index 1, etc. Consider what necessary steps you would need to sort an array.

Steps for Selection Sort Look for smallest element in the array. –Compare two elements to find the smaller of the two and hold its index. –If array holds class objects – need member function, friend function, or overloaded operator. (Should know how to code these.) Swap two elements when out of order.

#include using namespace std; void sort(int array[ ], int size); int main() { int array[]={7,3,9,18,15}; int i, size = 5; for (i = 0; i<size; i++) cout<<array[i]<<" "; sort(array, size); cout<<endl; for (i = 0; i<size; i++) cout<<array[i]<<" "; return(0); } void sort(int array[ ], int size) { int temp; int Index; for(int i=0; i<size-1; i++) {// place correct value in array[i] temp = array[i]; Index = i; // find smallest for(int j=i +1; j<size; j++) if(array[j] < temp) { temp = array[j]; Index = j; } // swap elements temp = array[i]; array[i] = array[Index]; array[Index] = temp; }

Swap Two Elements Suppose the array holds integers… Suppose the array holds doubles… Suppose the array holds Parts… What is the difference between the three sets of code above?

Template Functions Write a template function when the function can be used on a variety of different types with “virtually” no change in the code. The type is determined by the calling statement and can change with each call to the function.

Template Sort Function template void sort(T array[ ], int size) { T temp; int Index; for(int i=0; i<size-1; i++) {// place correct value in array[i] temp = array[i]; Index = i; // find smallest for(int j=i +1; j<size; j++) if(array[j] < temp) { temp = array[j]; Index = j; } // swap elements temp = array[i]; array[i] = array[Index]; array[Index] = temp; }

#include using namespace std; template void sort(T array[ ], int size); int main() { int array[]={7,3,9,18,15}; int i, size = 5; for (i = 0; i<size; i++) cout<<array[i]<<" "; sort(array, size); cout<<endl; for (i = 0; i<size; i++) cout<<array[i]<<" "; return(0); } template void sort(T array[ ], int size) { T temp; int Index; for(int i=0; i<size-1; i++) {// place correct value in array[i] temp = array[i]; Index = i; // find smallest for(int j=i +1; j<size; j++) if(array[j] < temp) { temp = array[j]; Index = j; } // swap elements temp = array[i]; array[i] = array[Index]; array[Index] = temp; }

#include using namespace std; template void sort(T array[ ], int size); int main() { double array[]={7.1,3.6,9.0,18.7,15.2}; int i, size = 5; for (i = 0; i<size; i++) cout<<array[i]<<" "; sort(array, size); cout<<endl; for (i = 0; i<size; i++) cout<<array[i]<<" "; return(0); } template void sort(T array[ ], int size) { T temp; int Index; for(int i=0; i<size-1; i++) {// place correct value in array[i] temp = array[i]; Index = i; // find smallest for(int j=i +1; j<size; j++) if(array[j] < temp) { temp = array[j]; Index = j; } // swap elements temp = array[i]; array[i] = array[Index]; array[Index] = temp; }

#include using namespace std; template void sort(T array[ ], int size); int main() { char array[]={'f','a','7','B','c'}; int i, size = 5; for (i = 0; i<size; i++) cout<<array[i]<<" "; sort(array, size); cout<<endl; for (i = 0; i<size; i++) cout<<array[i]<<" "; return(0); } template void sort(T array[ ], int size) { T temp; int Index; for(int i=0; i<size-1; i++) {// place correct value in array[i] temp = array[i]; Index = i; // find smallest for(int j=i +1; j<size; j++) if(array[j] < temp) { temp = array[j]; Index = j; } // swap elements temp = array[i]; array[i] = array[Index]; array[Index] = temp; }

Break into 2 functions template void sort(T array[], int size) { T temp; int NextSmallestIndex; for(int i=0; i<size-1; i++) {// place correct value in array[i] // find smallest NextSmallestIndex = findMin(array, i, size); // swap elements temp = array[i]; array[i] = array[NextSmallestIndex]; array[NextSmallestIndex] = temp; } template int findMin(const T array[], int start_index, int size) { T min = array[start_index]; int minIndex = start_index; for(int i=start_index +1; i<size; i++) { if(array[i] < min) { min = array[i]; minIndex = i; } return minIndex; }

Vectors When an array is created, it must have a declared size and this size cannot change during the program. A vector can be thought of as an array that can grow (and shrink) in length while your program is running.

Vector Basics Like an array, a vector has a base type and stores a collection of elements of this type. The vector class is a templated class. You must #include Declaration syntax: vector name; example – vector scores;

Vectors - Syntax You must include: #include Vector Declaration: vector name; Example: vector scores;

Using Vectors Vector elements are indexed the same as arrays –(starting at zero). You can use the square brackets [ ] to change the value stored in a vector element.

Adding Vectors Elements The first time you add an element to the vector, you must use a function called push_back( ). The function’s parameter is of the same type as the vector elements.

Example vector sample; sample.push_back(0.0); sample.push_back(1.1); sample.push_back(2.2);

Vector Size The vector class has a function called size that will return the number of elements currently held. The size function returns an unsigned integer. –You will receive a warning if you store size in a regular integer. unsigned int x; x = sample.size();

Printing a Vector Like arrays, vectors are printed using a for-loop: for(unsigned int i=0; i< sample.size( ); i++) cout << sample[i] << endl;

Special Declarations You can initialize a primitive vector to a particular size with default elements using this notation: vector sample(10); –This vector will have size=10 and each of these 10 elements will equal zero. –To add any additional elements you would have to use the push_back function.

Over-running a Vector Provided you always use the push_back function, you will never need to worry about over-running a vector. –Note: You can over-run a vector using the square brackets. –When accessing vector elements, take care that the index inside the brackets never exceeds the size-1.

Removing Vector Elements To remove vector elements use the member function: –pop_back( ); vector sample; sample.push_back(3); sample.push_back(5); sample.push_back(4); 354 sample.size( ); 3

Removing Vector Elements Removing an element from the back of the vector. vector sample; sample.push_back(3); sample.push_back(5); sample.push_back(4); sample.pop_back( ); 35 sample.size( ); 2

Other Functions Every vector has a size and a capacity. Capacity is the number of elements which the vector is currently allocated to hold. –This is a memory control or efficiency issue and not one we will concern ourselves with at this time. –More vector member functions:.capacity();.empty();