int[] arr = {1, 2, 3, 4};int temp = arr[0];arr[0] = arr[3];arr[3] = temp;
时间: 2023-11-25 14:07:25 浏览: 61
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}.
相关问题
static void Main(string[] args) { int[] arr = { 5, 1, 4, 2, 8 }; int temp; for (int i = 0; i < arr.Length; i++) { for (int j = 0; j < arr.Length - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j + 1]; arr[j + 1] = arr[j]; arr[j] = temp; } } } for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i] + " "); } Console.ReadKey(); } } class QuickSort { static void Main01(string[] args) { int[] arr = { 10, 7, 8, 9, 1, 5 }; int n = arr.Length; QuickSort_Recursive(arr, 0, n - 1); Console.WriteLine("Sorted array:"); Console.WriteLine(string.Join(" ", arr)); } static void QuickSort_Recursive(int[] arr, int start, int end) { if (start < end) { int partitionIndex = Partition(arr, start, end); QuickSort_Recursive(arr, start, partitionIndex - 1); QuickSort_Recursive(arr, partitionIndex + 1, end); } } static int Partition(int[] arr, int start, int end) { int pivot = arr[end]; int i = (start - 1); for (int j = start; j < end; j++) { if (arr[j] <= pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp1 = arr[i + 1]; arr[i + 1] = arr[end]; arr[end] = temp1; return i + 1; }
这段代码是在进行排序。
其中第一个 Main 函数实现了冒泡排序,它将一个整数数组进行排序,并在排序后输出。
第二个 Main 函数实现了快速排序,它将一个整数数组进行排序,并在排序后输出。它使用了递归来实现快速排序。
import java.util.Arrays; public class test { //交换一三,二四 public test1(int[] arr){//方法 int temp=arr[0]; arr[0]=arr[2]; arr[2]=temp; temp=arr[1]; arr[1]=arr[3]; arr[3]=temp; System.out.println(Arrays.toString(arr)); }
//测试 public static void main(String[] args) { int[] arr={1,2,3,4}; test t=new test(); t.test1(arr); } }
阅读全文