Array algorithms for replacing element values

Lesson content

  • About algorithms for replacing (values of) array elements
  • Replacing a value in a specific position in the array
  • Replacing a specific value in an array at all found positions
  • Replacing a specific value in an array (first or last found)
  • Shifting all elements of an array by one position “right” or “left”
  • Most common errors

About algorithms for replacing (values of) array elements

Replacing the values of array elements involves taking the existing value of one or more elements from the array and replacing them with another value. Typically, two values are involved:

  • The value to be replaced (“old”)
  • The value to replace the “old” value (“new”)

The “old” value can be:

  • A specific value (e.g., replacing the number 500 or the letter ‘A’)
  • Or a set of values expressed by some rule (for example, replacing all numbers in the array that are greater than 300)

Similarly, the “new” value can be:

  • A specific value (e.g., replace all negative numbers with the number 1000)
  • Or a value derived from the old value through some rule/transformation (e.g., add 10% to all prices in the array)

In the simplest case, the value of one array element is replaced at a precisely specified position in the array. For example, set the value of the fifth element in the prices array to 1200 dollars. In this case, the algorithm is the same as for adding a new value at a specific position in the array, except that this position was not “free” before, so the old value is actually replaced with the new value (“overwritten”) by entering the new value at the same position.

Replacement can involve replacing all array elements that have the “old” value. For example, replacing all ‘A’ characters in an array with the letter ‘B’.

Replacement can also involve replacing the “old” value of only one element, but without knowing its position in advance (e.g., the first or last found element in the array with the “old” value). For example, replace the first found profit (from an array of profits) greater than 3000 dollars with a profit of 1000 dollars.

Furthermore, there are cases where it is necessary to shift all array elements by one position “right” or “left”, and the algorithmic solutions for this can also be considered algorithms for replacing values of array elements. This typically involves sequentially replacing the value of each array element with the value of the next or previous element in the array, until all elements are processed. We have covered a similar algorithm in the previous lesson when inserting a value in the array requires all subsequent elements to be moved one place to the right to make a free spot.

Algorithmically, when replacing values in array elements, the FOR-EACH loop cannot be used, and other characteristics of these algorithms are as follows:

  • The value of one or more elements in the array is changed — from the “old” value to the “new” value.
  • They most often involve finding the array element(s) that contain the “old” value.
  • The algorithm stops once the value is replaced only if the value of one array element is being replaced. If the value of multiple elements is being replaced, the algorithm does not stop until the entire array is processed.

Replacing a value in a specific position in the array

As stated, this is the simplest case in which only one element of the array is being changed, and its exact position (index) is known (specified) in advance. More often than not, it includes cases where the full array capacity is used, and each element has a clearly defined meaning — for example, a bus seat array or monthly profits array.

For example, it is necessary to replace the price for the month of May (in an array of monthly prices) with a new price of 1200 dollars - the May price being the fifth array element.

In this form, the replacement is done without any prior search or check of the “old” value because the position of the element whose value needs to be changed is already known. From an algorithmic point of view, a loop is not needed, so the entire algorithm boils down to a single line of code:

1 array[index] = newValue;

Although this looks like adding a new value into the array, the differences are that:

  • The desired element is not a “free spot” in the array, it already contains some concrete value - which is being replaced by another value.
  • The array counter (if used) is not incremented by one, because the total number of entered values hasn’t increased — only an existing value is being replaced with another.

Example 1

Create a class MonthlyTemperatures that has:

  • An attribute monthlyTemperatures, which represents an array of average temperatures in a certain city (e.g., 23.1) for each of the 12 months of the year. The first element in the array refers to January, the second to February, and so on, with the last referring to December (e.g., 123.44). The array should be initialized immediately upon declaration.
  • A constructor that takes an array of exactly 12 elements as a parameter, representing the monthly temperatures. This constructor copies the array into the monthlyTemperatures attribute.
  • A method replaceTemperature that replaces the existing temperature for a specific month with a new value. The first parameter is the ordinal number of the month, and the second is the new average temperature for that month. Note that the months are numbered from 1 to 12, while array indices go from 0 to 11.
  • A method print that prints all the monthly temperatures using a FOR loop.
 1     class MonthlyTemperatures {
 2 
 3         double[] monthlyTemperatures = new double[12];
 4 
 5         MonthlyTemperatures(double[] monthlyTemperatures){
 6             this.monthlyTemperatures = monthlyTemperatures;
 7         }
 8 
 9         void replaceTemperature(int month, double newTemperature){
10             monthlyTemperatures[month -1] = newTemperature;
11         }
12 
13         void print(){
14             for (int i = 0; i < monthlyTemperatures.length; i++)
15                 System.out.println(monthlyTemperatures[i]);
16         }
17 
18     }

Create a class TestMonthlyTemperatures that, in the main method, creates an object of the MonthlyTemperatures class with arbitrary temperatures for each month. Then, replace the temperature for January with a value of -5.0 degrees and print all monthly temperatures to the screen.

 1     class TestMonthlyTemperatures {
 2 
 3         public static void main(String[] args) {
 4             double[] monthlyTemperatures =
 5                     {-3.4, 2.2, 8.1, 13.8, 17.3, 23.1,
 6                             29.1, 28.5, 20.3, 12.9, 7.6, 6.7};
 7             MonthlyTemperatures mt = new MonthlyTemperatures(monthlyTemperatures);
 8 
 9             mt.replaceTemperature(1,-5.0);
10 
11             mt.print();
12         }
13     }

The algorithm for replacing the value of an element at a specific position is implemented in the replaceTemperature method. Since the full array (its full capacity) is used here, and it’s known exactly which element corresponds to which value (each element represents one month of the year), there is no need to search for the element with the “old” value — so a FOR loop is not required. The replacement is done at a precisely defined position in the array — in this case, the month number minus one represents the index in the array where the “old” value should be replaced with the “new” one.

That’s why it is necessary for the method to receive the month number as a parameter, along with the new temperature value.

In many real-life scenarios, arrays are not used to their full capacity. Instead of replacing the value at a specific position, the replacement algorithm first needs to search for the element that contains the “old” value. Variations include finding all such elements, or the first or last such element in the array, but the replacement step is always the same once the correct element (elements) is found.

Replacing a specific value in an array at all found positions

As time passes, as the array is used, its elements take on specific values (they no longer represent “free spaces” in the array). At some point, it may be necessary to go through the array and replace the value of a specific element with another value. The most common way to replace values of array elements is to set the values of all found array elements that have the “old” value to the “new” value. For example, replace all ‘A’ letters (from a character array) with ‘B’, or replace all negative values (from a number array) with zeros.

As mentioned, the “old” value can be given as a specific value or as a range of values (through some condition), so in any case, the algorithm involves going through the entire array and searching for elements with the “old” value. The “new” value can also be a specific value, but it can also be derived from the “old” value through some transformation.

In any case, a FOR loop is used, where the loop counter goes through all index values (from 0 to length-1, or from 0 to counter-1, depending on whether an element counter is used). In each iteration, (through a nested IF statement), the value of the current array element is checked, and if the element contains the “old” value, that element is replaced with the “new” value.

Example 2

Create a class ProductPrices that has:

  • An attribute prices that represents an array of prices for multiple products (e.g., 123.44).
  • A constructor that takes an array of product prices as a parameter and sets the prices attribute to that array.
  • A method replaceNegatives that goes through the array of prices and replaces every negative price with zero.
  • A method increaseLowPrices that takes a percentage value as a parameter (e.g., 10.5%) and increases all prices in the array that are less than 100 dollars by that percentage.
  • A method print that prints all elements of the array from the first to the last.
 1     class ProductPrices {
 2 
 3         double[] prices;
 4 
 5         ProductPrices(double[] prices){
 6             this.prices = prices;
 7         }
 8 
 9         void replaceNegatives(){
10             for (int i = 0; i < prices.length; i++)
11                 if (prices[i] < 0)
12                     prices[i] = 0;
13         }
14 
15         void increaseLowPrices(double increasePercentage){
16             for (int i = 0; i < prices.length; i++)
17                 if (prices[i] < 100)
18                     prices[i] = prices[i] * ((100 + increasePercentage) / 100);
19         }
20 
21         void print(){
22             for (int i = 0; i < prices.length; i++)
23                 System.out.print(prices[i] + " ");
24 
25             System.out.println();
26         }
27 
28     }

Create a class TestProductPrices that creates one object of the ProductPrices class in the main method, and inputs the following array of prices: {123.45, -78.99, 33.00, -1.0, 20.59}. After the input, print all the prices, then replace the negative prices with zeros, then print all the prices again. Then increase all low prices by 10% and print all the prices once more.

 1     class TestProductPrices {
 2 
 3         public static void main(String[] args) {
 4             double[] prices =
 5                     {123.45, -78.99, 33.00, -1.0, 20.59};
 6 
 7             ProductPrices pp = new ProductPrices(prices);
 8 
 9             pp.print();
10 
11             pp.replaceNegatives();
12 
13             pp.print();
14 
15             pp.increaseLowPrices(10);
16 
17             pp.print();
18         }
19     }

The replaceNegatives method contains an algorithm for replacing all negative prices in the array (the “old” value) with zero (the “new” value). A FOR loop is used to iterate through all elements of the array, and a nested IF statement checks whether the current element is less than zero (prices[i] < 0), i.e., if it matches the “old” value. If it does, the “new” value (zero) is assigned to that element (prices[i] = 0). Since all negative prices need to be changed, the FOR loop does not terminate early (break or return), but instead always iterates through the entire array.

A similar algorithm is used in the increaseLowPrices method. The “old” value is any price less than 100 dollars, while the “new” value is derived by increasing the old price by the given percentage. Again, a FOR loop is used to go through all elements of the array, and a nested IF statement checks whether the element has the “old” value — i.e., whether the price is less than 100 (prices[i] < 100). If so, the price is increased by the given percentage, and that becomes the new value of the element:

1 prices[i] = prices[i] * ((100 + increasePercentage) / 100);

If an element counter (number of actual entered prices) is used instead of the full array length, these replacement algorithms would remain the same, but would iterate through the entered elements only (from index 0 to counter - 1 instead of from 0 to length - 1).

Replacing a specific value in an array (first or last found)

In some situations, it is necessary to go through an array and replace a specific (“old”) value of an array element with another value. However, the position of the element containing that value is not known in advance. Specifically, it is most common to replace the first or last element of the array that has that value. However, before replacing, the array is searched for that value in the following way:

  • From the beginning of the array to the end until an element with that value is found (first element) or
  • From the end of the array to the beginning until an element with that value is found (last element).

Example 3

Create the ProductPrices2 class by altering the ProductPrices class. This class should have :

  • An attribute named prices representing an array of prices for multiple products (e.g., 123.44).
  • A constructor that takes an array of prices as a parameter and sets it as the value of the prices attribute.
  • A method replaceFirst that takes the old price and the new price as parameters and finds the first element in the array (from the start) with the old price. The method changes the value of that element to the new price.
  • A method replaceLast that takes the old price and the new price as parameters and finds the last element in the array (the first element when looking from the end) with the old price. The method changes the value of that element to the new price.
  • A method print that prints all elements of the array from the first to the last on the screen.
 1     class ProductPrices2 {
 2 
 3         double[] prices;
 4 
 5         ProductPrices2(double[] prices){
 6             this.prices = prices;
 7         }
 8 
 9         void replaceFirst(double oldPrice, double newPrice){
10             for (int i = 0; i < prices.length; i++)
11                 if (prices[i] == oldPrice) {
12                     prices[i] = newPrice;
13                     break;//or return;
14                 }
15         }
16 
17         void replaceLast(double oldPrice, double newPrice){
18             for (int i = prices.length-1; i >= 0; i--)
19                 if (prices[i] == oldPrice) {
20                     prices[i] = newPrice;
21                     break;//or return;
22                 }
23         }
24 
25 
26         void print(){
27             for (int i = 0; i < prices.length; i++)
28                 System.out.println(prices[i]);
29         }
30 
31     }

Create a class TestProductPrices2 which in the main method creates an object of the ProductPrices2 class containing five prices: 100.0, 200.0, 300.0, 200.0, and 500.0. Then, the first element in the array with the price 200.0 is changed to the price 123.45, and the last element in the array with the price 200.0 is changed to the price 545.02. Finally, the print method should be called.

 1     class TestProductPrices2 {
 2 
 3         public static void main(String[] args) {
 4             double[] prices = {100.0, 200.0, 300.0, 200.0, 500.0};
 5 
 6             ProductPrices2 pp = new ProductPrices2(prices);
 7 
 8             pp.replaceFirst(200.0, 123.45);
 9 
10             pp.replaceLast(200.0, 545.02);
11 
12             pp.print();
13         }
14     }

The method replaceFirst changes the old price with the new price for the first element in the array containing the old price. A for loop goes through all the indices of the array (0 to length-1), and a nested if statement checks whether the current array element contains the “old” price. If it does, the new price is entered into that array element, and the loop is stopped using a break statement (the entire method can also be terminated using a return statement).

It is very important that the method is terminated immediately after the replacement because otherwise, the search for the “old” price and the replacement with the new one would continue, meaning that the new price would be inserted instead of the “old” price in all places where the “old” price is found.

In the method replaceLast, a nearly identical algorithm is used, but it replaces the “old” price with the “new” price in the last element of the array that contains the “old” price. The only difference is that the for loop goes through the indices in reverse order (length-1 to 0), so the search for the first element with the “old” price, when viewed from the end of the array, actually becomes a search for the last such element when viewed from the beginning of the array.

It should be noted that introducing an array (element) counter in this case does not lead to a significant change in the previous algorithms, as the search still needs to be performed. The only difference is that the loop counter would not take values from 0 to length-1, but from 0 to counter-1, or from counter-1 to 0 if the array is traversed from the end to the beginning.

Shifting all elements of an array by one position “right” or “left”

One of the commonly used algorithms is the one where all the elements of the array are shifted by one position “left” (“shift left”) or “right” (“shift right”). A similar algorithm was discussed in the lesson on algorithms for inserting elements to an array — when it was necessary to “free” one position in the array before entering a new value by shifting the other elements one position to the “right”.

How does this shifting work in practice? Let’s say we have the following array of letters:

1 {'A', 'B', 'C', 'X', 'Z'}

Shifting all elements by one position to the “right” means that the last element (‘Z’) moves to the first position, and all the others shift one position towards the end of the array:

1 {'A',-> 'B',-> 'C',-> 'X',-> 'Z'}
2   ^                           |
3   |                           |
4  'Z'  <-    <-    <-    <-   <-

After shifting right, the array would look like this:

1 {'Z', 'A', 'B', 'C', 'X'}

Shifting all the elements of the initial array by one position to the “left” means that the first element (‘A’) moves to the last position, and all the other elements shift one position towards the start of the array:

1 {'A',<- 'B',<- 'C',<- 'X',<- 'Z'}
2   |                           ^
3   |                           |
4   ->    ->    ->    ->    -> 'A'

After shifting left, the array would look like this:

1 {'B', 'C', 'X', 'Z', 'A'}

These algorithms work the same way even when the elements of the array have repeated values, and it is also possible to shift by more than one position to the right or left — although this is less common. A detailed explanation of both algorithms is given below.

Example 4

For example, let’s take the following array of numbers (the numbers are ordered in ascending order to make the example easier to follow, but they can be any numbers):

1 {10, 20, 30, 40}

Shifting by one position to the right involves first declaring a helper variable where the value of the last array element (i.e., number 40) will be temporarily stored. This is done so that the value of this element is not lost while shifting the other elements to the right.

1 First, a helper variable ("tmp") should be created and
2 the value of the last element should be stored in it:
3         tmp = 40
4               ^
5               |
6 {10, 20, 30, 40}

Then, the right shift is done by copying number 30 to the last (4th) position in the array, then number 20 to the 3rd position, and finally number 10 to the 2nd position in the array. This order of operations is important so that no values are overwritten. For example, if number 10 is copied “right” first to the 2nd position, it would overwrite the number 20. The following step-by-step representation shows the process:

 1 First, number 30 is copied to the 4th position:
 2 tmp = 40
 3 {10, 20, 30,-> 40}
 4 
 5 And now we have number 30 in two places:
 6 tmp = 40
 7 {10, 20, 30, 30}
 8 
 9 Then, number 20 is copied to the 3rd position:
10 tmp = 40
11 {10, 20,-> 30, 30}
12 
13 And this "overwrites" the previous number 30, but now we have number 20 in two places:
14 tmp = 40
15 {10, 20, 20, 30}
16 
17 Then, number 10 is copied to the 2nd position:
18 tmp = 40
19 {10,-> 20, 20, 30}
20 
21 And this "overwrites" the previous number 20, but now we have number 10 in two places:
22 tmp = 40
23 {10, 10, 20, 30}

Finally, the number 40 from the helper variable “tmp” is placed in the first position of the array, completing the right shift.

1 The number 40 is copied from the helper variable to the first position:
2 {10, 10, 20, 30}
3   ^
4   |
5 tmp = 40
6 
7 This "overwrites" the duplicate of number 10, and the array now looks like this:
8 {40, 10, 20, 30}

One common mistake is copying the array elements to the right starting from the first element: moving the first element to the second position, the second element to the third, and so on. This actually causes the values to be lost (overwritten) as the value of the first element is set in all positions in the array:

1 {10,-> 20, 30, 40} => {10, 10, 30, 40}
2 
3 {10, 10,-> 30, 40} => {10, 10, 10, 40}
4 
5 {10, 10, 10,-> 40} => {10, 10, 10, 10}

If it’s a left shift, the algorithm is very similar, except the value of the first element is stored in the helper variable, and then the shift happens from the second element to the first, from the third to the second, and so on.

Example 5

Let’s consider the same array of numbers as in the previous example:

1 {10, 20, 30, 40}

Shifting by one position to the left involves first declaring a helper variable where the value of the first element of the array (i.e., number 10) will be temporarily stored. This is done so that the value of this element is not lost while shifting the other elements to the left.

1 First, a helper variable ("tmp") should be created and the value of the first element should be stored in it:
2 tmp = 10
3  ^
4  |
5 {10, 20, 30, 40}

Then, the left shift is done by copying number 20 to the first position, then number 30 to the 2nd position, and finally number 40 to the 3rd position in the array. This order of operations is important so that no values are overwritten. For example, if number 40 is copied “left” first to the 3rd position, it would overwrite number 30. The following step-by-step representation shows the process:

 1 First, number 20 is copied to the first position:
 2 tmp = 10
 3 {10, <-20, 30, 40}
 4 
 5 And now we have number 20 in two places:
 6 tmp = 10
 7 {20, 20, 30, 40}
 8 
 9 Then, number 30 is copied to the 2nd position:
10 tmp = 10
11 {20, 20, <-30, 40}
12 
13 And this "overwrites" the previous number 20, but now we have number 30 in two places:
14 tmp = 10
15 {20, 30, 30, 40}
16 
17 Then, number 40 is copied to the 3rd position:
18 tmp = 10
19 {20, 30, 30, <-40}
20 
21 And this "overwrites" the previous number 30, but now we have number 40 in two places:
22 tmp = 10
23 {20, 30, 40, 40}

Finally, the number 10 from the helper variable “tmp” is placed in the last position of the array, completing the left shift.

1 The number 10 is copied from the helper variable to the last position:
2 {20, 30, 40, 40}
3               ^
4               |
5         tmp = 10
6 
7 This "overwrites" the duplicate of number 40, and the array now looks like this:
8 {20, 30, 40, 10}

A common mistake is to copy the array elements to the left starting from the last element and moving toward the first: the last element to the second-to-last (third) position, the third element to the second position, and so on. This actually causes the values to be lost (overwritten), as the value of the last element is set in all positions in the array:

1 {10, 20, 30, <-40} => {10, 20, 40, 40}
2 
3 {10, 20, <-40, 40} => {10, 40, 40, 40}
4 
5 {10, <-40, 40, 40} => {40, 40, 40, 40}

Example 6

Create a class MonthlyTemperatures2 which has:

  • An attribute monthlyTemperatures which represents an array of average temperatures for a city (e.g., 23.1) for each of the 12 months of the year. The first element of the array corresponds to January, the second to February, and so on, with the last element corresponding to December (e.g., 123.44). The array should be quickly initialized immediately upon declaration with arbitrary temperatures for each month of the year.
  • A method shiftLeft that shifts all elements of the array by one position “left.” The first element of the array should be moved to the last position.
  • A method shiftRight that shifts all elements of the array by one position “right.” The last element of the array should be moved to the first position.
  • A method print that prints all the monthly temperatures using a FOR loop, all in one line on the screen.
 1     class MonthlyTemperatures2 {
 2 
 3         double[] monthlyTemperatures = {-3.4, 2.2, 8.1, 13.8, 17.3, 23.1,
 4                 29.1, 28.5, 20.3, 12.9, 7.6, 6.7};
 5 
 6         void shiftLeft(){
 7             double tmp = monthlyTemperatures[0];
 8 
 9             for (int i = 0; i < monthlyTemperatures.length-1; i++)
10                 monthlyTemperatures[i] = monthlyTemperatures[i+1];
11 
12             monthlyTemperatures[monthlyTemperatures.length-1] = tmp;
13         }
14 
15         void shiftRight(){
16             double tmp = monthlyTemperatures[monthlyTemperatures.length-1];
17 
18             for (int i = monthlyTemperatures.length-1; i > 0; i--)
19                 monthlyTemperatures[i] = monthlyTemperatures[i-1];
20 
21             monthlyTemperatures[0] = tmp;
22         }
23 
24         void print(){
25             for (int i = 0; i < monthlyTemperatures.length; i++)
26                 System.out.print(monthlyTemperatures[i] + " ");
27 
28             System.out.println();
29         }
30 
31     }

Create a class TestMonthlyTemperatures2 which, in the main method, creates two objects of the MonthlyTemperatures2 class. First, print all the monthly temperatures of the first object, then shift them left and print them again. After that, print all th e monthly temperatures of the second object, then shift them right and print them again.

 1     class TestMonthlyTemperatures2 {
 2 
 3         public static void main(String[] args) {
 4             MonthlyTemperatures2 mt = new MonthlyTemperatures2();
 5             System.out.println("Before and after a shift to the left");
 6             mt.print();
 7             mt.shiftLeft();
 8             mt.print();
 9 
10 
11             MonthlyTemperatures2 mt2 = new MonthlyTemperatures2();
12             System.out.println("Before and after a shift to the right");
13             mt2.print();
14             mt2.shiftRight();
15             mt2.print();
16         }
17     }

The algorithm for the left shift in the shiftLeft method first involves storing the value of the first element of the array in a helper variable (double tmp = monthlyTemperatures[0];). This is done to preserve the value of this element from being “overwritten” when the second element is shifted to the left, i.e., its value is copied to the first position.

After that, within the FOR loop, the value of each subsequent element is copied into the previous one (monthlyTemperatures[i] = monthlyTemperatures[i+1];). It is important that this is done in this order so that the value of the next element is copied first into the previous element and then, in the next iteration, it is “overwritten” with the value of its next element.

Additionally, the FOR loop counter goes from 0 to length-2 (not length-1) because in each iteration of the loop, both the current element (index i) and the next element (index i+1) are used. So, in the final iteration, the monthly temperature for November (i has the value 10 because length-2 = 12 - 2 = 10) will get the value of the monthly temperature for December (i+1 has the value 11, i.e., monthlyTemperatures[10] = monthlyTemperatures[11];). If the loop were to continue with another iteration, the counter i would get the value 11, and i+1 would be 12 (an index out-of-bounds error would occur when trying to execute the line of code for copying the element value left: monthlyTemperatures[11] = monthlyTemperatures[12];).

At the end, the value of the helper variable is placed into the last element of the array (the first element is moved to the end of the array), and the entire algorithm is completed (monthlyTemperatures[monthlyTemperatures.length-1] = tmp;).

The algorithm for the right shift in the shiftRight method is very similar. First, the value of the last element of the array is stored in a helper variable (double tmp = monthlyTemperatures[monthlyTemperatures.length-1];). This is done to preserve the value of this element from being “overwritten” when the second-to-last element is shifted to the right, i.e., its value is copied to the last position of the array.

After that, within the FOR loop, the value of each element is copied into the next one (monthlyTemperatures[i] = monthlyTemperatures[i-1];). It is important that this is done in this order so that the value of the previous element is copied first into the next element and then, in the next iteration, it is “overwritten” with the value of its previous element. Additionally, the FOR loop counter goes “backwards” from length-1 to 1 (not to 0) because in each iteration, both the current element (index i) and the previous element (index i-1) are used. If the loop counter went to 0, in the final iteration it would have a value of 0, and i-1 would be -1 (an invalid value for an index), which would result in an error when trying to execute the line of code to copy the element value to the right: monthlyTemperatures[0] = monthlyTemperatures[-1];).

At the end, the value of the helper variable is placed into the first element of the array (the last element is moved to the start of the array), completing the algorithm (monthlyTemperatures[0] = tmp;).

Most common errors

Some of the most common errors related to algorithms for swapping values of array elements that are not syntax errors, but affect the operation of the program, are:

  • Using a FOR-EACH loop to swap the values of array elements, for example:
1       void replaceNegatives() {
2           for (int price: prices)
3               if (price < 0)
4                   price = 0;
5       }

Instead, the correct approach is to use a FOR loop:

1       void replaceNegatives() {
2           for (int i = 0; i < prices.length; i++)
3               if (prices[i] < 0)
4                   prices[i] = 0;
5       }
  • Forgetting to break the loop after swapping the value of the first or last element in the array that has the “old” value, or forgetting to use the break or return statement, for example:
1       void replaceFirst(double oldPrice, double newPrice) {
2           for (int i = 0; i < prices.length; i++)
3               if (prices[i] == oldPrice) {
4                   prices[i] = newPrice;
5               }
6       }

Instead, the correct approach is:

1       void replaceFirst(double oldPrice, double newPrice) {
2           for (int i = 0; i < prices.length; i++)
3               if (prices[i] == oldPrice) {
4                   prices[i] = newPrice;
5                   break; // or return;
6               }
7       }
  • When swapping values for all array elements with the “old” value and using a counter for the elements, iterating through the array until the full length of the array (length-1) instead of using the counter (counter-1):
1       void replaceAllNegatives() {
2           for (int i = 0; i < prices.length; i++)
3               if (prices[i] < 0)
4                   prices[i] = 0;
5       }

Instead, the correct approach is:

1       void replaceAllNegatives() {
2           for (int i = 0; i < counter; i++)
3               if (prices[i] < 0)
4                   prices[i] = 0;
5       }
  • When swapping values for a specific element in the array (when the array is at full capacity), forgetting to subtract one from the element’s position to match the index in the array (e.g., using 1 for January instead of index 0):
1       void replaceTemperature(int month, double newTemperature) {
2           monthlyTemperatures[month] = newTemperature;
3       }

Instead, the correct approach is:

1       void replaceTemperature(int month, double newTemperature) {
2           monthlyTemperatures[month-1] = newTemperature;
3       }
  • When shifting elements of an array to the left, forgetting that the FOR loop counter should go from 0 to length-2 (not length-1) because in each iteration, both the current element (index i) and the next element (index i+1) are used:
1       void shiftLeft() {
2           double tmp = monthlyTemperatures[0];
3     
4           for (int i = 0; i < monthlyTemperature.length; i++)
5               monthlyTemperatures[i] = monthlyTemperatures[i+1];
6     
7           monthlyTemperatures[monthlyTemperature.length-1] = tmp;
8       }

Instead, the correct approach is:

1       void shiftLeft() {
2           double tmp = monthlyTemperatures[0];
3     
4           for (int i = 0; i < monthlyTemperature.length-1; i++)
5               monthlyTemperatures[i] = monthlyTemperatures[i+1];
6     
7           monthlyTemperatures[monthlyTemperature.length-1] = tmp;
8       }
  • When shifting elements of an array to the left, copying the next element to the previous one, but starting from the end of the array towards the beginning (the FOR loop counter goes “backwards”). The mistake here is that by starting from the end of the array, the value of the last element is copied to every preceding one, thus overwriting all other values in the array:
1       void shiftLeft() {
2           double tmp = monthlyTemperatures[0];
3     
4           for (int i = monthlyTemperature.length-1; i > 0; i--)
5               monthlyTemperatures[i-1] = monthlyTemperatures[i];
6     
7           monthlyTemperatures[monthlyTemperature.length-1] = tmp;
8       }

Instead, the correct approach is:

1       void shiftLeft() {
2           double tmp = monthlyTemperatures[0];
3     
4           for (int i = 0; i < monthlyTemperature.length-1; i++)
5               monthlyTemperatures[i] = monthlyTemperatures[i+1];
6     
7           monthlyTemperatures[monthlyTemperature.length-1] = tmp;
8       }
  • When shifting elements of an array to the right, forgetting that the FOR loop counter should go from length-1 to 1 (not to 0) because in each iteration, both the current element (index i) and the previous element (index i-1) are used:
1       void shiftRight() {
2           double tmp = monthlyTemperatures[monthlyTemperature.length-1];
3     
4           for (int i = monthlyTemperature.length-1; i >= 0; i--)
5               monthlyTemperatures[i] = monthlyTemperatures[i-1];
6     
7           monthlyTemperatures[0] = tmp;
8       }

Instead, the correct approach is:

1       void shiftRight() {
2           double tmp = monthlyTemperatures[monthlyTemperature.length-1];
3     
4           for (int i = monthlyTemperature.length-1; i > 0; i--)
5               monthlyTemperatures[i] = monthlyTemperatures[i-1];
6     
7           monthlyTemperatures[0] = tmp;
8       }
  • When shifting elements of an array to the right, copying the previous element into the next one, but starting from the beginning of the array towards the end (the FOR loop counter goes “normally”). The mistake here is that by starting from the beginning of the array, the value of the first element is copied to every subsequent one, overwriting all other values in the array:
1       void shiftRight() {
2           double tmp = monthlyTemperatures[monthlyTemperature.length-1];
3     
4           for (int i = 0; i < monthlyTemperature.length-1; i++)
5               monthlyTemperatures[i+1] = monthlyTemperatures[i];
6     
7           monthlyTemperatures[0] = tmp;
8       }

Instead, the correct approach is:

1       void shiftRight() {
2           double tmp = monthlyTemperatures[monthlyTemperature.length-1];
3     
4           for (int i = monthlyTemperature.length-1; i > 0; i--)
5               monthlyTemperatures[i] = monthlyTemperatures[i-1];
6     
7           monthlyTemperatures[0] = tmp;
8       }