gpt-3.5-turbo-0301· OpenAI
WildChat-4.8M (AI2)
write a java swap function
- User
write a java swap function
- Assistant
Here is an example of a Java swap function that swaps the values of two variables:
javapublic static void swap(int[] arr, int i, int j) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; }This function takes in an integer array
arr, and two indicesiandj, representing the positions of the elements that need to be swapped. It then creates a temporary variabletempto hold the value of the element at indexi, and assigns the value of the element at indexjto indexi. Finally, it assigns the value oftempto indexj, effectively swapping the values of the two elements.