I am attempting to translate two separate algorithms into Java code in order to test them; the first algorithm (PrefixAverages1) is:
For i = 0 to n-1
Let s = X[0]
For j = 1 to i
Let s = s + X[j]
End For
Let A[i] = s / (i + 1)
End For
Output: An n-element array A of numbers such that A[i] is the average of elements X[0], X[1], ..., X[i].
This is the Java translation that I came up with for PrefixAverages1:
import java.util.Arrays;
public class PrefixAverages1 {
static double array[] = new double[10];
public static void prefixAverages(){
for (int i = 0; i < 10; i++){
double s = array[i];
for (int j = 0; j < 10; j++){
s = s + array[j];
}
array[i] = s / (i + 1);
System.out.println(Arrays.toString(array));
}
}
public static void main(String[] args){
prefixAverages();
}
}
The second algorithm (PrefixAverages2) is:
Let s = X[0]
For i = 0 to n-1
Let s = s + X[i]
Let A[i] = s / (i + 1)
End For
Output: An n-element array A of numbers such that A[i] is the average of elements X[0], X[1], ..., X[i].
This is the Java translation that I came up with for PrefixAverages2:
import java.util.Arrays;
public class PrefixAverages2 {
static double array[] = new double[10];
public static void prefixAverages(){
double s = 0;
for (int i = 0; i < 10; i++){
s = s + array[i];
array[i] = s / (i + 1);
}
array[0] = 10;
System.out.println(Arrays.toString(array));
}
public static void main(String[] args){
prefixAverages();
}
}
I am attempting to test the algorithms but am not quite sure where to start. I am attempting to set up an array and then apply these algorithms on it by running through them by hand for small values of n.
Where/how would I begin to add elements to the array to begin with?
I am also trying to analyse both algorithms by counting primitive operations and derive T(n) for both algorithms. I would like to be able to work out the time complexity (Big Oh, O(n)) of each algorithm and discover which one is the most efficient.
Any help with this would be greatly appreciated.
Thanks for taking the time to read and assist.
A[]vsX[]). - Mark Peters