Swapping array elements

 

One of the most common operations performed on arrays is to swap two elements.   As an example, consider our array numbers from before and suppose we’d like to swap the first with the last element.

 

      numbers     (before the swap)     

 

 


2

3

6

8

11

                    0          1           2           3            4                       

 

 

      numbers     (after the swap)

 

 


11

3

6

8

2

                    0          1           2           3            4                       

 

Swapping requires us to create a temporary variable to save one of the elements to be swapped, numbers[0] and numbers[4] (let’s save numbers[0]).  The value of numbers[4] is then assigned to numbers[0].  And finally, we copy the value of temp containing the saved value of numbers[0] to numbers[4].  Diagrammatically, this is what we’re trying to accomplish:

 

 

 

      numbers     (3 steps to swapping) 

 

 

 


2 11

3

6

8

11 2

                    0          1           2           3            4                       

Text Box: step 3Text Box: step 1       

                                   

   2

                                    temp

 

In code, this would translate to:

 

      int temp = numbers[0];

      numbers[0] = numbers[4];

      numbers[4] = temp;