int[] arr = {1, 2, 3, 4};int temp = arr[0];arr[0] = arr[3];arr[3] = temp;
时间: 2023-11-25 21:07:25 浏览: 51
This code swaps the first and last elements of the integer array "arr". The initial value of the array is {1, 2, 3, 4}.
The first line initializes the array with 4 integers.
The second line creates a temporary variable "temp" and assigns it the value of the first element of the array (which is 1).
The third line assigns the value of the fourth element of the array (which is 4) to the first element of the array.
The fourth line assigns the value of the temporary variable "temp" (which is 1) to the fourth element of the array.
After executing this code, the value of the array would be {4, 2, 3, 1}.
相关问题
int[] arr3 = { 2,1,3,5,6,4,7,9,8 } 进行 排序 升序 降序
对于给定的数组 int[] arr3 = { 2,1,3,5,6,4,7,9,8 },可以使用不同的排序算法来实现升序和降序排序。
升序排序:
一种常见的升序排序算法是冒泡排序。它通过多次遍历数组,比较相邻元素并交换位置,将较大的元素逐渐移动到数组的末尾。以下是使用冒泡排序实现升序排序的示例代码:
```java
int[] arr3 = { 2,1,3,5,6,4,7,9,8 };
int n = arr3.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr3[j] > arr3[j + 1]) {
int temp = arr3[j];
arr3[j] = arr3[j + 1];
arr3[j + 1] = temp;
}
}
}
```
降序排序:
另一种常见的降序排序算法是选择排序。它通过多次遍历数组,每次选择最大的元素并将其放置在已排序部分的开头。以下是使用选择排序实现降序排序的示例代码:
```java
int[] arr3 = { 2,1,3,5,6,4,7,9,8 };
int n = arr3.length;
for (int i = 0; i < n - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr3[j] > arr3[maxIndex]) {
maxIndex = j;
}
}
int temp = arr3[i];
arr3[i] = arr3[maxIndex];
arr3[maxIndex] = temp;
}
```
以上代码分别使用冒泡排序和选择排序对数组进行了升序和降序排序。排序后的结果存储在数组 arr3 中。
解释以下代码:public void push(int item) { if (size == arr.length) { int[] temp = new int[arr.length * 2]; for (int i = 0; i < arr.length; i++) { temp[i] = arr[i]; } arr = temp; arr = Arrays.copyOf(arr, arr.length * 2); } arr[size++] = item; } public void pop() { arr[--size] = 0 } public int size = 0; public int[] arr = new int[2];
这段代码实现了一个栈(stack)的数据结构,具体解释如下:
1. `push(int item)` 方法用于将一个元素压入栈中,如果栈已满,则将栈扩容到原来的两倍大小。具体扩容方式是,创建一个长度为原数组长度两倍的临时数组 `temp`,并将原数组 `arr` 中的元素全部复制到 `temp` 中,然后将 `arr` 指向 `temp`,最后使用 `Arrays.copyOf()` 方法将 `arr` 数组的长度再次扩容到原来的两倍。
2. `pop()` 方法用于弹出栈顶元素。由于栈顶元素的下标是 `size-1`,因此可以使用 `--size` 将 `size` 减一后将对应下标的元素设置为 0。
3. `size` 表示栈中元素的个数,初始值为 0。
4. `arr` 是存储栈元素的数组,初始长度为 2。当栈中元素个数达到数组长度时,需要调用 `push()` 方法进行扩容。