java排序代码怎么写


有很多种排序算法可以在Java中实现,以下是一些常见的排序算法的示例代码:
1. 冒泡排序(Bubble Sort)
```java
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
// 交换arr[j]和arr[j+1]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
}
```
2. 插入排序(Insertion Sort)
```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;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
}
```
3. 选择排序(Selection Sort)
```java
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
}
// 交换arr[i]和arr[minIndex]
int temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
}
```
这些只是排序算法中的几个示例,还有很多其他的排序算法,如快速排序、归并排序等。你可以根据具体的需求选择合适的排序算法。


上一篇:Android bindservice失败的原因和解决方法是什么

下一篇:java中ArrayList的排序方法有哪些


蚂蚁钢琴网 2008-2025 somall.com.cn 皖ICP备2023010105号
大写数字 热点城市 热点地区 热点街道 热点时间 房贷计算器
钢琴调律 钢琴调音 钢琴调律价格
温馨提示:部分文章图片数据来源与网络,仅供参考!版权归原作者所有,如有侵权请联系删除!
违法和不良信息24小时举报热线:18056540210