给定一个非负整数数组A (A中元素不相同,如存在元素相同,则提示用户重新输入),返回一个数组,在该数组中的所有整数从小到大排列。 示例: 输入:A=[1,5,3,8,6,2] 输出:[1,2,3,5,6,8] 分别使用合并排序和快速排序,使用Java实现。
时间: 2024-11-25 08:13:51 浏览: 2
给定一个数n如23121;给定一组数字a中元素组成的小于n的最大数
要给定一个非负整数数组并按照升序排列,你可以使用多种排序算法。这里我会展示如何使用 Java 实现这两种常见排序算法:归并排序(Merge Sort)和快速排序(Quick Sort)。请注意,虽然题目没有明确指定,但在实际编程中,通常我们不会在排序过程中对原数组进行操作,而是创建一个新的数组存储结果。
**归并排序(Merge Sort):**
```java
public class Solution {
public int[] mergeSort(int[] nums) {
if (nums.length <= 1) {
return nums;
}
int mid = nums.length / 2;
int[] left = new int[mid];
int[] right = new int[nums.length - mid];
System.arraycopy(nums, 0, left, 0, mid);
System.arraycopy(nums, mid, right, 0, nums.length - mid);
return merge(mergeSort(left), mergeSort(right));
}
private int[] merge(int[] left, int[] right) {
int[] merged = new int[left.length + right.length];
int i = 0, j = 0, k = 0;
while (i < left.length && j < right.length) {
if (left[i] <= right[j]) {
merged[k++] = left[i++];
} else {
merged[k++] = right[j++];
}
}
while (i < left.length) {
merged[k++] = left[i++];
}
while (j < right.length) {
merged[k++] = right[j++];
}
return merged;
}
}
```
**快速排序(Quick Sort):**
```java
public class Solution {
public int[] quickSort(int[] nums) {
if (nums == null || nums.length <= 1) {
return nums;
}
int pivotIndex = partition(nums, 0, nums.length - 1);
int[] sorted = Arrays.copyOfRange(nums, 0, pivotIndex + 1);
sorted = mergeArrays(sorted, quickSort(Arrays.copyOfRange(nums, pivotIndex + 1, nums.length)));
return sorted;
}
private int partition(int[] nums, int low, int high) {
int pivotValue = nums[high];
int i = (low - 1);
for (int j = low; j < high; j++) {
if (nums[j] < pivotValue) {
i++;
swap(nums, i, j);
}
}
swap(nums, i + 1, high);
return i + 1;
}
private void swap(int[] nums, int i, int j) {
int temp = nums[i];
nums[i] = nums[j];
nums[j] = temp;
}
private int[] mergeArrays(int[] arr1, int[] arr2) {
int[] merged = new int[arr1.length + arr2.length];
System.arraycopy(arr1, 0, merged, 0, arr1.length);
System.arraycopy(arr2, 0, merged, arr1.length, arr2.length);
return merged;
}
}
```
阅读全文