In your text file write a function that reverses an array of ints: void reverse(int* array, int numElements){ // your code here } Example input: int a[6] = {3,6,8,1,3,6} reverse(a, 6); // should result in {6,3,1,8,6,3}
时间: 2023-03-16 21:44:36 浏览: 56
答案:void reverse(int* array, int numElements){
int i, j, temp;
for (i = 0, j = numElements - 1; i < j; i++, j--) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
相关问题
Write a function that reverses its string argument.
好的,下面是一个可以将字符串反转的函数的 Python 代码:
```
def reverse_string(s):
return s[::-1]
```
该函数将字符串作为参数传入,并通过步长为 -1 的切片操作对字符串进行反转,最后返回反转后的字符串。例如:
```
>>> reverse_string("hello world")
'dlrow olleh'
```
用java Implement the function to reverse an array.
Sure, here's an example implementation of a function to reverse an array in Java:
```java
public static void reverseArray(int[] arr) {
int left = 0;
int right = arr.length - 1;
while (left < right) {
// Swap the elements at the left and right indices
int temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
// Move the left and right indices inwards
left++;
right--;
}
}
```
To use this function, you would pass in an array of integers like this:
```java
int[] arr = {1, 2, 3, 4, 5};
reverseArray(arr);
System.out.println(Arrays.toString(arr)); // Output: [5, 4, 3, 2, 1]
```
This function works by initializing two pointers, `left` and `right`, at opposite ends of the array. It then swaps the elements at these indices and moves the pointers inwards until they meet in the middle. This effectively reverses the order of the elements in the array.