java编程实现对一维整形数组排列
时间: 2024-09-27 09:10:20 浏览: 43
在 Java 中,我们可以使用数组排序算法(如冒泡排序、选择排序、插入排序、快速排序等)来对一维整型数组进行排列。这里以快速排序为例,它是一种高效的通用排序算法,适用于大多数情况。
**快速排序示例**:
```java
public class QuickSortIntArray {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) {
// 找到基准元素并分割数组
int pivotIndex = partition(arr, low, high);
// 对左右两个部分递归地进行排序
quickSort(arr, low, pivotIndex - 1); // 左半部分
quickSort(arr, pivotIndex + 1, high); // 右半部分
}
}
private static int partition(int[] arr, int low, int high) {
// 通常选择最后一个元素作为基准
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
// 交换元素
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// 将基准元素放到正确的位置
int temp2 = arr[i + 1];
arr[i + 1] = arr[high];
arr[high] = temp2;
return i + 1;
}
// 示例:对整个数组进行排序
public static void main(String[] args) {
int[] array = {9, 5, 2, 7, 1, 8, 6};
quickSort(array, 0, array.length - 1);
for (int num : array) {
System.out.print(num + " ");
}
}
}
```
运行上述程序后,你会看到一维整型数组按升序排列的结果。如果你想了解其他排序算法的实现或者其他特定需求,可以告诉我哦。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045021.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)