Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More

Recipe 5.1. Swapping Two Elements in an Array

Problem

You want an efficient method to swap two elements that exist within a single array.

Solution

Use the generic SwapElementsInArray<T> method:

public static void SwapElementsInArray<T>(T[] theArray, int index1, int index2) { if (index1 >= theArray.Length || index2 >= theArray.Length || index1 < 0 || index2 < 0) { throw(new ArgumentOutOfRangeException( "index passed in to this method is out of bounds.")); } else { T tempHolder = theArray[index1]; theArray[index1] = theArray[index2]; theArray[index2] = tempHolder; } }

Discussion

There is no specific method in the .NET Framework that allows you to swap only two specific elements within an array. The SwapElementsInArray method presented in this recipe allows for only two specified elements of an array (specified in the index1 and index2 arguments to this method).

The following code uses the SwapElementsInArray<T> method to swap the zeroth and fourth elements in an array of integers:

public static void TestSwapArrayElements() { int[] someArray = new int[5] {1,2,3,4,5}; for (int counter = 0; counter < someArray.Length; counter++) { Console.WriteLine("Element " + counter + " = " + someArray[counter]); } SwapElementsInArray(someArray, 0, 4); for (int counter = 0; counter < someArray.Length; counter++) { Console.WriteLine("Element " + counter + " = " + someArray[counter]); } }

This code produces the following output:

Element 0 = 1 The original array Element 1 = 2 Element 2 = 3 Element 3 = 4 Element 4 = 5 Element 0 = 5 The array with elements swapped Element 1 = 2 Element 2 = 3 Element 3 = 4 Element 4 = 1

Категории