就地分揀 - 這是當你來自外部,給你,而不是創造一些新的陣列和以任何方式使用它們原來的陣列,上運行。就地分揀花費O(1)的空間,而不是爲O(n)+使用時附加的數據structres
實施例的就地排序:
public static void simpleBubbleSort(int[] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 1; j < arr.length; j++) {
if (arr[j - 1] > arr[j]) {
swap(arr, j - 1, j);
}
}
}
}
與之相對排序合併沿着方式創建陣列,並且最後將它們組合起來並返回NOT而不是原來的(給予我們的)數組,而是包含結果的數組。
public static int[] mergeSort(int[] arr) {
if (arr.length < 2) return arr;
int mid = arr.length/2;
int[] left = new int[mid];
int[] right = new int[mid + arr.length % 2];
int j = 0;
for (int i = 0; i < arr.length; i++) {
if (i < mid) {
left[i] = arr[i];
} else {
right[j++] = arr[i];
}
}
// keeps going until there's 1 element in each array[]
return mergeReturn(mergeSort(left), mergeSort(right));
}
private static int[] mergeReturn(int[] leftArr, int[] rightArr) {
int leftPointer = 0, rightPointer = 0, combinedSize = leftArr.length + rightArr.length;
int[] merged = new int[combinedSize];
for (int i = 0; i < combinedSize; i++) {
if (leftPointer < leftArr.length && rightPointer < rightArr.length) {
if (leftArr[leftPointer] < rightArr[rightPointer]) {
merged[i] = leftArr[leftPointer++];
} else {
merged[i] = rightArr[rightPointer++];
}
} else if (leftPointer < leftArr.length) { // adding the last element
merged[i] = leftArr[leftPointer++];
} else {
merged[i] = rightArr[rightPointer++];
}
}
return merged;
}
的可能的複製[就地快速排序中的Java(http://stackoverflow.com/questions/29609909/inplace-quicksort-in-java) –