Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming.

Slides:



Advertisements
Similar presentations
Lesson 8 Searching and Sorting Arrays 1CS 1 Lesson 8 -- John Cole.
Advertisements

One Dimensional Arrays
Programming and Data Structure
1 Various Methods of Populating Arrays Randomly generated integers.
Copyright © 2014, 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Eighth Edition by Tony Gaddis,
Chapter 9: Searching, Sorting, and Algorithm Analysis
 Sort: arrange values into an order  Alphabetical  Ascending numeric  Descending numeric  Does come before or after “%”?  Two algorithms considered.
Visual C++ Programming: Concepts and Projects
Copyright © 2012 Pearson Education, Inc. Chapter 8: Searching and Sorting Arrays.
Sorting1 Sorting Order in the court!. sorting2 Importance of sorting Sorting a list of values is a fundamental task of computers - this task is one of.
1 Sorting/Searching CS308 Data Structures. 2 Sorting means... l Sorting rearranges the elements into either ascending or descending order within the array.
C++ Plus Data Structures
 2003 Prentice Hall, Inc. All rights reserved Sorting Arrays Sorting data –Important computing application –Virtually every organization must sort.
Arrays Data Structures - structured data are data organized to show the relationship among the individual elements. It usually requires a collecting mechanism.
CS 106 Introduction to Computer Science I 10 / 15 / 2007 Instructor: Michael Eckmann.
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 9 Searching.
CS 106 Introduction to Computer Science I 10 / 16 / 2006 Instructor: Michael Eckmann.
Computer Science: A Structured Programming Approach Using C1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C.
Describing algorithms in pseudo code To describe algorithms we need a language which is: – less formal than programming languages (implementation details.
Chapter 8 ARRAYS Continued
Week 11 Introduction to Computer Science and Object-Oriented Programming COMP 111 George Basham.
COMP102 Lab 131 COMP 102 Programming Fundamentals I Presented by : Timture Choi.
Chapter 9: Advanced Array Concepts
Lists in Python.
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
Applications of Arrays (Searching and Sorting) and Strings
Computer Science Searching & Sorting.
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.
CSC141- Introduction to Computer programming Teacher: AHMED MUMTAZ MUSTEHSAN Lecture – 19 Thanks for Lecture Slides:
Searching and Sorting, Template Functions, and Vectors ITK 169 Fall 2003.
ARRAY Prepared by MMD, Edited by MSY1.  Introduction to arrays  Declaring arrays  Initializing arrays  Examples using arrays  Relationship with pointers.
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 The concept of arrays Using arrays Arrays as arguments Processing an arrays data Multidimensional arrays Sorting data in an array Searching with.
BUILDING JAVA PROGRAMS CHAPTER 7 Arrays. Exam #2: Chapters 1-6 Thursday Dec. 4th.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
1 Today’s Material Iterative Sorting Algorithms –Sorting - Definitions –Bubble Sort –Selection Sort –Insertion Sort.
Computer Science 101 Introduction to Sorting. Sorting One of the most common activities of a computer is sorting data Arrange data into numerical or alphabetical.
Chapter 14: Searching and Sorting
Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Modified for use by MSU Dept. of Computer Science.
Chapter 5 Searching and Sorting. Copyright © 2004 Pearson Addison-Wesley. All rights reserved.1-2 Chapter Objectives Examine the linear search and binary.
1 Objectives ❏ To understand the basic concepts and uses of arrays ❏ To be able to define C arrays ❏ To be able to pass arrays and array elements to functions.
CSCI 51 Introduction to Programming March 12, 2009.
Searching & Sorting Programming 2. Searching Searching is the process of determining if a target item is present in a list of items, and locating it A.
Sorting CS Sorting means... Sorting rearranges the elements into either ascending or descending order within the array. (we’ll use ascending order.)
Sorting Algorithms: Selection, Insertion and Bubble.
1 Searching and Sorting Searching algorithms with simple arrays Sorting algorithms with simple arrays –Selection Sort –Insertion Sort –Bubble Sort –Quick.
Arrays An array is a data object that can hold multiple objects, all of the same type. We can think of an array as a storage box which has multiple compartments.
Array Search & Sort (continues). On the fly questions Array declaration: int[] a, b, c; 1. a is an array of integers, b and c are two integers 2. a, b,
Prepared by MMD, Edited by MSY1 CHAPTER 4 ARRAY. Prepared by MMD, Edited by MSY2 Arrays  Introduction to arrays  Declaring arrays  Initializing arrays.
Course Code #IDCGRF001-A 5.1: Searching and sorting concepts Programming Techniques.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 14 Searching and Sorting.
Data Structures Arrays and Lists Part 2 More List Operations.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
Arrays Department of Computer Science. C provides a derived data type known as ARRAYS that is used when large amounts of data has to be processed. “ an.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 8: Searching and Sorting Arrays.
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.
Searching and Sorting Arrays
Introduction to Search Algorithms
Average Monthly Temperature and Rainfall
Objectives At the end of the class, students are expected to be able to do the following: Understand the purpose of sorting technique as operations on.
Selection Sort – an array sorting algorithm
Searching and Sorting Arrays
Searching and Sorting Arrays
Introduction to Sorting Algorithms
Sorting.
Presentation transcript:

Common Elementary Algorithms Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: a)Some programming languages including Java make them a standard part of their definition. b)Every scholar studying computer science should understand them from first principle. Algorithms: a)List some or all the elements in an array. b)List array elements in the reverse order of how they were stored. c)Find aggregate, mean, and the standard deviation of numeric arrays. d)Search and sort arrays.

Process Array In Reverse Order Sometimes it is necessary to access the elements of an array in the reverse order in which they were stored. This concept requires you to understand the indexing format of an array firmly. That is, given an array arr of size N, the first index value is 0 and the last, N-1. The format is: for (int i = N-1; i >= 0; i-- ) statement;

Processing Parallel Arrays The following arrays show the average monthly rainfall for a given year: double rainfall[] = {6.2, 7.2, 9.5, 10.8, 8.1, 7.5, 7.7, 11.3, 12.4, 15.9, 7.9, 12.5}; String[] months = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec“ };

Print Quarterly Print array values in reverse order of the rainfall reading for each ending quarter. Traversal the array for all of the data values. The array index ranges from 0 to rainfall.length - 1 (11) inclusive. There are four quarters in the year so divide the index range by three. The values must be printed when the indices are: 11, 8, 5, and 2. Hence, the printing must be done when index % 3 is 2. 1.String Print() 2.{ 3. String s = “”; 4. for (int i = rainfall.length-1; i >= 0; i--) 5. if (i%3 == 2) 6. s = s + months[i] + " " + rainfall[i] + "\n"); 7. return s; 8.}

Sum Values This exercise follows similar pattern to the previous exercise. The array must be traversed. As each element is encountered it gets added to for the aggregate. 1.double sumArray() 2.{ 3. double sum = 0; for (int i = 0; i < rainfall.length; i++) 6. sum = sum + rainfall [i]; return sum; 9.}

Finding Average Once the aggregate is known the average is found by simply dividing the aggregate by the number of readings. 1.double average() 2.{ 3. return sumArray()/rainfall.length; 4.}

List Elements above average This exercise requires: Getting the average, and Traversing the list comparing the average to each array element. When you find an element that is larger than the average, a note is made of it. 1.String aboveAvarage() 2.{ 3. String s = ""; 4. double avg = average(); 5. for (int i = 0; i < rainfall.length; i++) 6. if (rainfall [i] > avg) 7. s = months[i] + " " + rainfall[i] + "\n"; 8. return s; 9.}

Array – Finding Standard Deviation The standard deviation is the square root of the sum of the squared difference of an observation and the mean, divided by the number of observations. That is, s =  (  (x i – ū ) 2 /N), i є [0, MAX] The expression  (x i - ū) 2 can be expressed as follows: sumDifference = sumDifference + Math.pow((rainfall [i] - mean), 2); where: (x i - ū) 2 is Math.pow((rainfall [i] - mean), 2); x i is rainfall [i] ū is the mean (average)that was already calculated, and MAX is rainfall.length – 1

Standard Deviation - Code 1.double standardDeviation() 2.{ 3. double sumDifference = 0; double mean = average(); for (int i = 0; i < rainfall.length; i++) 8. sumDifference = sumDifference + Math.pow((rainfall [i] - mean), 2); return Math.sqrt(sumDifference/rainfall.length); 11.}

Find Highest Value Consider the following array 1. What is the highest value in the array? 2. How do we find the highest value? Look at is this way:

Find the largest element in an array Look at it this way: The largest values we’ve seen so far is 25. So initially 25 is the largest value. The next value will be 4 Then 65, which makes 65 the largest so far. Continues this way to the last element, by which time the largest is found

Finding Largest Value - Code 1.double findHighestReading() 2. { 3. double highestSoFar = rainfall[0]; for(int i = 1; i < length; i ++) 6. if ( rainfall [i] > highestsofar ) 7. highestSoFar = rainfall [i]; return highestSoFar; 10. }

Array - Graphing Using the arrays – months and rainfall. For each month print x number of stars from the rainfall array. Convert each rainfall value to the nearest integer, and Print that many stars. That is: for each month { int x = (int) Math.floor(rainfall[i]) print x number of stars }

Make Horizontal Bar Graph 1.String makeGraph() 2. { 3. String s = ""; 4. for (int i = 0; i < length; i++) 5. { 6. s = s + months[i] + " "; 7. int x = (int) Math.floor( rainfall[i] ); for(int j = 1; j <=x; j++) 10. s = s + "*"; 11. s = s + "\n"; 12. } 13. return s; 14. }

Copy Array To make a backup copy of an array do the following: a)Create an array of equal size, and b)Copy the elements one by one into the newly created array. Note: Given that arr is a one dimensional array, say: int arr[] = {2, 4, 6, 8}; arr

Assignment vs. Copy Consider the statement int x[] = arr; The statement has the following effect: arr x

Arrays Assign References Consider the following statements: x[1] = 28; x[2] = 34; The following code has the following effect: arr x

Create Copy 1.class RainfallReading 2.{ 3. // ……. 4. String copy_months[]; 5. //…… RainfallReading (double r[], String months[]) 8. { 9. copy_months = new String[months.length]; for (int i = 0; i < months.length; i++) 12. copy_months[i] = months[i]; } 15. //….. 16.}

Search - Linear A search yields three pieces of information: 1.If the item looking for is found 2.The position it is found in the list 3.What item is found in the list Provide accessor methods to return each value. class RainfallReading { boolean found; // Yes or no if item is found int index; // Position where item is found if it is in the list double item; // The item itself. // …….. }

Linear Search 1.void search(double key) 2.{ 3.int i = 0; 4.while (i < rainfall.length && ! found) 5.if ( key == rainfall[i]) 6.{ 7. found = true; 8. index = i; 9. item = rainfall[i]; 10. } 11.else 12. i++; 13.}

Linear Search 1.boolean inList() 2.{ 3. return found; 4.} 1.double getItem() 2.{ 3. return item; 4.} 1.int getIndex() 2.{ 3. return index; 4.}

Selection Sort Sort - to arrange a list in either ascending or descending order. There are many sorting algorithms Insertion sort, Bubble sort, and Selection sort, to name a few. The sorting algorithm discussed here is the selection sort. The algorithm requires the following two steps: 1.Find the location of the smallest element in the unsorted portion of the list. 2.Exchange/swap the element at the position with the first element in the unsorted portion of the list.

Selection Sort [0][1][2][3][4][5][6][7][8][9] [0][1][2][3][4][5][6][7][8][9] Initially the beginning the entire list is unsorted. Find the position of the smallest element in the list, The smallest element is at position 7 Exchange it with the value at position 0.

Selection Sort [0][1][2][3][4][5][6][7][8][9] The unsorted portion of the list begins at index 1 Find the position of the smallest element in this portion of the list, The smallest element is at position 3 Exchange it with the value at position 1. [0][1][2][3][4][5][6][7][8][9]

Selection Sort [0][1][2][3][4][5][6][7][8][9] The unsorted portion of the list begins at index 2 Find the position of the smallest element in this portion of the list, The smallest element is at position 7 Exchange it with the value at position 2. [0][1][2][3][4][5][6][7][8][9]

Selection Sort [0][1][2][3][4][5][6][7][8][9] The unsorted portion of the list begins at index 3 Find the position of the smallest element in this portion of the list, The smallest element is at position 7 Exchange it with the value at position 3. [0][1][2][3][4][5][6][7][8][9]

Selection Sort [0][1][2][3][4][5][6][7][8][9] The unsorted portion of the list begins at index 4 Find the position of the smallest element in this portion of the list, The smallest element is at position 4 Exchange it with the value at position 4. [0][1][2][3][4][5][6][7][8][9] The pattern continues until the entire list is sorted.

Selection Sort Applying this to the RainfallReading class. Here is a skeletal outline of the algorithm. for (int startScan = 0; startScan < rainfall.length – 1; startScan ++) { int position = findPosition(startScan ); swap( position, startScan ); } int findPosition(int startScan ) { // define method } void swap( int minIndex, int startScan ) { // define method }

Selection Sort 1.void selectionSort() 2.{ 3.for (int startScan = 0; startScan < rainfall.length - 1; startScan++ ) 4.{ 5.int position = findPosition(startScan); 6.swap(position, startScan); 7.} 8.}

Selection Sort int findPosition(int startScanFrom) 3.{ 4.int position = from; 5. 6.for (int i = startScanFrom + 1; i < rainfall.length; i++) 7.if (rainfall[i] < rainfall[position]) 8.position = i; return position; 11.}

Selection Sort 1. void swap(int i, int j) 2.{ 3.// Swap the rainfalls 4. double temp = rainfall[i]; 5.rainfall[i] = rainfall[j]; 6.rainfall[j] = temp; // Swap the months 9. String str = months[i]; 10. months[i] = months[j]; 11. months[j] = str; 12.}