Title: Common Elementary Algorithms
1Common 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.
2Process 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 gt 0 i-- )
- statement
3Processing 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
4Print 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 gt 0
i--) - if (i3 2)
- s s monthsi "
" rainfalli "\n") - return s
-
5Sum 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 lt rainfall.length i)
- sum sum rainfall i
-
- return sum
6Finding 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
7List 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 lt rainfall.length
i) - if (rainfall i gt avg)
- s monthsi " "
rainfalli "\n" - return s
8Array 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 u )2/N), i ? 0, MAX
- The expression ?(xi - u)2 can be expressed as
follows - sumDifference sumDifference
Math.pow((rainfall i - mean), 2) - where
- (xi - u)2 is Math.pow((rainfall i - mean),
2) -
- xi is rainfall i
- u is the mean (average)that was already
calculated, and - MAX is rainfall.length 1
9Standard Deviation - Code
- double standardDeviation()
-
- double sumDifference 0
-
- double mean average()
-
- for (int i 0 i lt rainfall.length i)
- sumDifference sumDifference
Math.pow((rainfall i - mean), 2) -
- return Math.sqrt(sumDifference/rainfall.lengt
h)
10Find 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
11Find the largest element in an array
- Look at it this way
- The largest values weve 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
12Finding Largest Value - Code
-
- double findHighestReading()
-
- double highestSoFar rainfall0
-
- for(int i 1 i lt length i )
- if ( rainfall i gt highestsofar
) - highestSoFar rainfall
i -
- return highestSoFar
-
13Array - 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(rainfalli) -
- print x number of stars
-
14Make Horizontal Bar Graph
- String makeGraph()
-
- String s ""
- for (int i 0 i lt length i)
-
- s s monthsi " "
- int x (int) Math.floor(
rainfalli ) -
- for(int j 1 j ltx j)
- s s ""
- s s "\n"
-
- return s
-
15Copy 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
16Assignment vs. Copy
- Consider the statement
- int x arr
- The statement has the following effect
x
arr
17Arrays Assign References
- Consider the following statements
- x1 28
- x2 34
- The following code has the following effect
x
arr
18Create Copy
- class RainfallReading
-
- // .
- String copy_months
- //
-
- RainfallReading (double r, String
months) -
- copy_months new
Stringmonths.length -
- for (int i 0 i lt months.length
i) - copy_monthsi monthsi
-
-
- //..
19Search - 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.
- // ..
-
20Linear Search
-
- void search(double key)
-
- int i 0
- while (i lt rainfall.length ! found)
- if ( key rainfalli)
-
-
found true -
index i -
item rainfalli -
- else
- i
-
21Linear Search
- boolean inList()
-
- return found
-
- double getItem()
-
- return item
-
- int getIndex()
-
- return index
22Selection 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.
23Selection 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.
24Selection 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.
25Selection 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.
26Selection 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.
27Selection 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.
28Selection Sort
- Applying this to the RainfallReading class. Here
is a skeletal outline of the algorithm. - for (int startScan 0 startScan lt
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
-
29Selection Sort
- void selectionSort()
-
- for (int startScan 0 startScan lt
rainfall.length - 1 startScan ) -
- int position findPosition(startScan)
- swap(position, startScan)
-
30Selection Sort
-
- int findPosition(int startScanFrom)
-
- int position from
-
- for (int i startScanFrom 1 i lt
rainfall.length i) - if (rainfalli lt rainfallposition)
- position i
-
- return position
-
31Selection Sort
-
- void swap(int i, int j)
-
- // Swap the rainfalls
- double temp rainfalli
- rainfalli rainfallj
- rainfallj temp
-
- // Swap the months
- String str monthsi
- monthsi monthsj
- monthsj str
-