Please enable JavaScript to use CodeHS

Chapter 6

Arrays

6.4 Developing Algorithms Using Arrays

Programmers use data structures to store data. Data is often stored so that it can be used or analyzed at some point in the future. Array traversals have several important applications in regards to how data is used and analyzed. They can be used in:

Mathematical Analysis

  • Determine a minimum or maximum value
  • Compute a sum, average, or mode

Analyzing Element Properties

  • Determine if at least one element has a particular property
  • Determine if all elements have a particular property
  • Access all consecutive pairs of elements
  • Determine the presence or absence of duplicate elements
  • Determine the number of elements meeting specific criteria

Reordering Elements

  • Shift or rotate elements left or right
  • Reverse the order of the elements

Each of these subsets uses a distinct algorithm to analyze arrays.

Mathematical Traversal Algorithms

Computing mathematical results, such as the sum of integers in an array or finding the average of each value in an array requires the use of a similar algorithm:

int[] scores = {80, 92, 91, 68, 88};

//Initialize value here
int valueToFind = 0;

for (int i = 0; i < scores.length; i++){
   //Perform calculation on valueToFind
}

//Report results of valueToFind
Plain text

In each case, the algorithm requires the initialization of a value that will be used to store the result of a given computation outside of the for loop. Inside the loop, the initialized value, valueToFind, will be altered depending on the desired output, and the results will be displayed after the loop has terminated.

For a better understanding of this, consider this implementation of computing a sum:

int[] scores = {80, 92, 91, 68, 88};
int sum = 0;
for (int i = 0; i < scores.length; i++){
   sum += scores[i];
}
System.out.println(sum);
Plain text

The value of sum is changed each iteration through the for loop, adding the current score to the value of sum. This algorithm looks awfully similar to the one used to find the average value of an array:

int[] scores = {80, 92, 91, 68, 88};
int sum = 0;
for (int i = 0; i < scores.length; i++){
   sum += scores[i];
}
System.out.println((double) sum / scores.length);
Plain text

In both cases, the initialized value is declared before the for loop, used in mathematical computations within, and then displayed after its termination.

Property Analysis Algorithms

To determine if an element or a set of elements in an array meets specific criteria or has a specific set of properties, the following general algorithm can be used:

String[] grades = {"A","C","B","A","B"};

//Initialize tracker variable
for (int i = 0; i < grades.length; i++){
   //Conditionally check properties
}

//Report results here
Plain text

Similar to mathematical analysis, property analysis sets an initial tracker variable before the start of the for loop, and checks through each iteration if the element at a specific index meets the criteria. It then reports the findings after the loop has terminated.

In the following example, the tracker variable checks how many A’s there are in the grade array:

String[] grades = {"A","C","B","A","B"};

//Initialize tracker variable
int numAs = 0;

for (int i = 0; i < grades.length; i++){
//Conditionally check properties
   if (grades[i].equals("A")){
      numAs++;
   }
}

System.out.print("Number of A's: ");
System.out.println(numAs);
Plain text

In this case, the value of the tracker variable numAs increments if the element at each index is an A. These tracker variables can also be used to store a single value that changes depending on the condition. For example, finding the minimum value of a list looks similar to the previous example, but only stores a single value:

int[] scores = {80, 92, 91, 68, 88};

int minIndex = 0;

for (int i = 1; i < scores.length; i++){
   if (scores[i] < scores[minIndex]){
      minIndex= i;
   }
}
System.out.println(minIndex);
Plain text

Rather than increment, this tracker keeps track of the current minimum value in the list. If the value at the current index is less than the existing minimum, then the tracker is changed to reflect that.

Reordering Arrays

Another common array algorithm involves reordering or reversing our arrays. While this can be done in a few different ways, a common method is to create a new temporary array where a copy of the new order for values is stored. Once the new order is copied into the temporary array, it overwrites the original array with the temporary one:

int[] numbers = {1, 2, 3, 4, 5};
int[] temp = new int[numbers.length]; //Create default array

//Loop, but stop at the last element (edge case)
for (int i = 0; i < numbers.length - 1; i++){
    temp[i + 1] = numbers[i]; 
}
temp[0] = numbers[numbers.length - 1]; //Edge case
numbers = temp; //Copy over to the original array
Plain text

In this example, the algorithm is shifting the values in the array to the right by one. Rather than move the values in the existing array, a new array is created to store the values in the specified order. This removes the possibility that the original array gets altered accidentally, and that changes to the new array do not impact the original.

Finding the Minimum Value

Reordering an Array

Finding Duplicates

Check Your Understanding

  1. Incorrect Correct No Answer was selected Invalid Answer

    What will the following code segment output?

    String[] grades = {"A","C","B","C","B", "A"};
    
    int mystery = 0;
    
    for (int i = 0; i < grades.length; i++)
    {
        if (grades[i].equals("B")) 
        {
            mystery ++;
        }
    }
    
    System.out.println(mystery);
    Java

Exercise: Find the Median

Write a method called median that returns the median value in the array.

If the length of the array is odd, the median is the value in the center of the array.

If the length of the array is even, the median is the average of the two numbers in the center.

You may assume the array passed into this method will never be empty.

Sample output:

The median value of the EVEN array is 19.5
The median value of the ODD array is 22.0
Plain text

Hint: We’ve imported java.util.* for you, so you have a handy static method on Arrays that you can use called Arrays.sortso you can sort your array BEFORE finding the median.