java中int怎么排序
时间: 2023-05-20 17:06:05 浏览: 46
在Java中,可以使用Arrays.sort()方法对int数组进行排序。例如,以下代码将一个int数组按升序排序:
int[] arr = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
输出结果为:[1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]
相关问题
java中插入排序
Java 中插入排序的实现方式与其他语言类似,也是基于比较和交换元素的思路。以下是 Java 实现插入排序的示例代码:
```java
public class InsertionSort {
public static void insertionSort(int[] arr) {
int n = arr.length;
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
}
```
在这个示例代码中,`arr` 是待排序的一维数组。`insertionSort` 函数实现了插入排序的算法。该算法使用了一个 `key` 变量来保存当前待排序的元素,然后在已排序的序列中从后往前扫描,找到相应的位置并插入。
Java升序排序int数组
可以使用Arrays.sort(intArray)来对int数组进行升序排序。
例如:
```
int[] intArray = {5,2,8,1,9};
Arrays.sort(intArray);
```
排序后的数组为:[1, 2, 5, 8, 9]