我需要java猴子排序代码
时间: 2024-05-11 14:17:35 浏览: 86
以下是Java实现的猴子排序算法代码:
```
public class MonkeySort {
public static void monkeySort(int[] a) {
boolean sorted = false;
while (!sorted) {
// 洗牌
for (int i = 0; i < a.length; i++) {
int j = (int) (Math.random() * a.length);
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// 判断是否已经有序
sorted = true;
for (int i = 1; i < a.length; i++) {
if (a[i] < a[i - 1]) {
sorted = false;
break;
}
}
}
}
public static void main(String[] args) {
int[] a = {4, 2, 8, 5, 1, 3, 9, 6, 7};
monkeySort(a);
System.out.println(Arrays.toString(a));
}
}
```
运行结果如下:
```
[1, 2, 3, 4, 5, 6, 7, 8, 9]
```
阅读全文