在Java中,如果你想要对包含负数的数组进行排序,使得负数位于数组的左侧,正数位于右侧,你可以使用以下方法之一:
方法一:双指针法
public class ArraySort {
public static void sortArray(int[] array) {
int i = 0, j = array.length - 1;
while (i < j) {
// 找到左侧的正数
while (i < j && array[i] < 0) {
i++;
}
// 找到右侧的负数
while (i < j && array[j] >= 0) {
j--;
}
// 交换这两个数
if (i < j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
return array;
}
public static void main(String[] args) {
int[] array = {1, 3, -8, -9, 6, 9, 10, -2, 4, -5, 91, 55, -66, -33, 7};
sortArray(array);
System.out.println(Arrays.toString(array));
}
}
方法二:桶排序法
public class BucketSort {
public static void sortArray(int[] array) {
int max = Integer.MIN_VALUE;
int min = Integer.MAX_VALUE;
for (int num : array) {
max = Math.max(max, num);
min = Math.min(min, num);
}
int bucketSize = Math.max(1, (max - min) / (array.length + 1));
int bucketCount = (max - min) / bucketSize + 1;
int[][] buckets = new int[bucketCount][array.length];
for (int num : array) {
int bucketIndex = (num - min) / bucketSize;
buckets[bucketIndex][bucketSize - 1 - (num - min) % bucketSize]++;
}
int index = 0;
for (int bucketIndex = 0; bucketIndex < bucketCount; bucketIndex++) {
for (int i = bucketSize - 1; i >= 0; i--) {
while (buckets[bucketIndex][i] > 0) {
array[index++] = buckets[bucketIndex][i] * bucketSize + i;
buckets[bucketIndex][i]--;
}
}
}
}
public static void main(String[] args) {
int[] array = {1, 3, -8, -9, 6, 9, 10, -2, 4, -5, 91, 55, -66, -33, 7};
sortArray(array);
System.out.println(Arrays.toString(array));
}
}
方法三:三向切分快速排序法