1 / 31

Common Elementary Algorithms

Common Elementary Algorithms. Some of the basic but frequently used algorithms for manipulating arrays. These algorithms are so important that: Some programming languages including Java make them a standard part of their definition.

nigel-white
Download Presentation

Common Elementary Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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;

  3. 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“ };

  4. 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. • String Print() • { • String s = “”; • for (int i = rainfall.length-1; i >= 0; i--) • if (i%3 == 2) • s = s + months[i] + " " + rainfall[i] + "\n"); • return s; • }

  5. 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 . • double sumArray() • { • double sum = 0; • for (int i = 0; i < rainfall.length; i++) • sum = sum + rainfall [i]; • return sum; • }

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

  7. 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. • String aboveAvarage() • { • String s = ""; • double avg = average(); • for (int i = 0; i < rainfall.length; i++) • if (rainfall [i] > avg) • s = months[i] + " " + rainfall[i] + "\n"; • return s; • }

  8. 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 = ((xi – ū )2/N), i є [0, MAX] • The expression (xi - ū)2 can be expressed as follows: • sumDifference = sumDifference + Math.pow((rainfall [i] - mean), 2); • where: • (xi - ū)2 is Math.pow((rainfall [i] - mean), 2); • xi is rainfall [i] • ū is the mean (average)that was already calculated, and • MAX is rainfall.length – 1

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

  10. 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:

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

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

  13. 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 }

  14. Make Horizontal Bar Graph • String makeGraph() • { • String s = ""; • for (int i = 0; i < length; i++) • { • s = s + months[i] + " "; • int x = (int) Math.floor(rainfall[i]); • for(int j = 1; j <=x; j++) • s = s + "*"; • s = s + "\n"; • } • return s; • }

  15. Copy Array To make a backup copy of an array do the following: • Create an array of equal size, and • 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

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

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

  18. Create Copy • class RainfallReading • { • // ……. • String copy_months[]; • //…… • RainfallReading (double r[], String months[]) • { • copy_months = new String[months.length]; • for (int i = 0; i < months.length; i++) • copy_months[i] = months[i]; • } • //….. • }

  19. Search - Linear A search yields three pieces of information: • If the item looking for is found • The position it is found in the list • 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. // …….. }

  20. Linear Search • void search(double key) • { • int i = 0; • while (i < rainfall.length && ! found) • if ( key == rainfall[i]) • { • found = true; • index = i; • item = rainfall[i]; • } • else • i++; • }

  21. Linear Search • boolean inList() • { • return found; • } • double getItem() • { • return item; • } • int getIndex() • { • return index; • }

  22. 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: • Find the location of the smallest element in the unsorted portion of the list. • Exchange/swap the element at the position with the first element in the unsorted portion of the list.

  23. Selection Sort 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.

  24. Selection Sort • 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.

  25. Selection Sort • 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.

  26. Selection Sort • 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.

  27. Selection Sort • 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. The pattern continues until the entire list is sorted.

  28. 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 }

  29. Selection Sort • void selectionSort() • { • for (int startScan = 0; startScan < rainfall.length - 1; startScan++ ) • { • int position = findPosition(startScan); • swap(position, startScan); • } • }

  30. Selection Sort • int findPosition(int startScanFrom) • { • int position = from; • for (int i = startScanFrom + 1; i < rainfall.length; i++) • if (rainfall[i] < rainfall[position]) • position = i; • return position; • }

  31. Selection Sort • void swap(int i, int j) • { • // Swap the rainfalls • double temp = rainfall[i]; • rainfall[i] = rainfall[j]; • rainfall[j] = temp; • // Swap the months • String str = months[i]; • months[i] = months[j]; • months[j] = str; • }

More Related