92.4k views
5 votes
Given an array arr of type int , along withtwo int variables i and j , write some code thatswaps the values of arr[i] and arr[j] . Declare anyadditional variables as necessary.

User Crystark
by
5.8k points

1 Answer

2 votes

Answer:

Hi! I suppose that no matter the programming language that you need the algorithm, so I will do in pseudo-code.

myArray [int] = [1,2,3,4,5,"Hello","World"];

int i = 5;

int j = 2;

// Save the previous value before the swap

aux1 = myArray[i];

aux2 = myArray[j];

// Swap i & j

myArray[j] = aux1;

myArray[i] = aux2;

print(myArray)

// Out : myArray = [1,2,"Hello",4,5,3,"World"]

Explanation:

The trick is to save in two variables the previous value of the two position before change the array, just like that you can change the array and make the swap without lost the values.

I hope it's help you.

User Bstricks
by
5.7k points