Common Elementary Algorithms

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

description

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. - PowerPoint PPT Presentation

Transcript of Common Elementary Algorithms

Page 1: Common Elementary Algorithms

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.

Page 2: Common Elementary Algorithms

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;

Page 3: Common Elementary Algorithms

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

Page 4: Common Elementary Algorithms

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

Page 5: Common Elementary Algorithms

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;4. 5. for (int i = 0; i < rainfall.length; i++)6. sum = sum + rainfall [i];7. 8. return sum;9. }

Page 6: Common Elementary Algorithms

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

Page 7: Common Elementary Algorithms

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

Page 8: Common Elementary Algorithms

Array – Finding Standard DeviationArray – 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

Page 9: Common Elementary Algorithms

Standard Deviation - Code

1. double standardDeviation()2. {3. double sumDifference = 0;4. 5. double mean = average();6. 7. for (int i = 0; i < rainfall.length; i++)8. sumDifference = sumDifference + Math.pow((rainfall [i] - mean), 2);9. 10. return Math.sqrt(sumDifference/rainfall.length);11. }

Page 10: Common Elementary Algorithms

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:

25 4 65 80 10

Page 11: Common Elementary Algorithms

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

25 4 65 80 10

Page 12: Common Elementary Algorithms

Finding Largest Value - Code

1. double findHighestReading()

2. {

3. double highestSoFar = rainfall[0];

4.

5. for(int i = 1; i < length; i ++)

6. if ( rainfall [i] > highestsofar )

7. highestSoFar = rainfall [i];

8.

9. return highestSoFar;

10. }

Page 13: Common Elementary Algorithms

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 }

Page 14: Common Elementary Algorithms

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] );8. 9. for(int j = 1; j <=x; j++)10. s = s + "*";

11. s = s + "\n";

12. }

13. return s;

14. }

Page 15: Common Elementary Algorithms

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};

2

4

6

8

arr

Page 16: Common Elementary Algorithms

Assignment vs. Copy

• Consider the statement

• int x[] = arr;

• The statement has the following effect:

2

4

6

8

arr x

Page 17: Common Elementary Algorithms

Arrays Assign References

• Consider the following statements:

• x[1] = 28;

• x[2] = 34;

• The following code has the following effect:

2

28

36

8

arr x

Page 18: Common Elementary Algorithms

Create Copy1. class RainfallReading2. {3. // …….4. String copy_months[];5. //……6.7. RainfallReading (double r[], String months[])8. {9. copy_months = new String[months.length];10. 11. for (int i = 0; i < months.length; i++)12. copy_months[i] = months[i];13. 14. }15. //…..16. }

Page 19: Common Elementary Algorithms

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.

// ……..

}

Page 20: Common Elementary Algorithms

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

Page 21: Common Elementary Algorithms

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

Page 22: Common Elementary Algorithms

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.

Page 23: Common Elementary Algorithms

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 30 24 7 25 62 45 16 65 50

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

16 30 24 7 25 62 45 5 65 50

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.

Page 24: Common Elementary Algorithms

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 30 24 7 25 62 45 16 65 50

• 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]

5 7 24 30 25 62 45 16 65 50

Page 25: Common Elementary Algorithms

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 24 30 25 62 45 16 65 50

• 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]

5 7 16 30 25 62 45 24 65 50

Page 26: Common Elementary Algorithms

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 30 25 62 45 24 65 50

• 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]

5 7 16 24 25 62 45 30 65 50

Page 27: Common Elementary Algorithms

Selection Sort

[0] [1] [2] [3] [4] [5] [6] [7] [8] [9]

5 7 16 24 25 62 45 30 65 50

• 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]

5 7 16 24 25 62 45 30 65 50

The pattern continues until the entire list is sorted.

Page 28: Common Elementary Algorithms

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 }

Page 29: Common Elementary Algorithms

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

Page 30: Common Elementary Algorithms

Selection Sort

1.2. 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;9.10. return position;11. }

Page 31: Common Elementary Algorithms

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;

7.

8. // Swap the months

9. String str = months[i];

10. months[i] = months[j];

11. months[j] = str;

12. }