您好,登錄后才能下訂單哦!
代碼如下:
private void merge(int[] array, int left, int mid, int right) {
int i = left;
int j = mid;
int length = right - left;
int[] extra = new int[length];
int k = 0;
while(i < mid && j < right) {
if(array[i] <= array[j]) {
extra[k++] = array[i++];
} else {
extra[k++] = array[j++];
}
}
while (i < mid) {
extra[k++] = array[i++];
}
while (j < right) {
extra[k++] = array[j++];
}
// 從 extra 搬移回 array
for (int t = 0; t < length; t++) {
// 需要搬移回原位置,從 low 開始
array[left + t] = extra[t];
}
}
遞歸實現操作:
public void mergeSort(int[] array) {
mergeSortInternal(array, 0, array.length);
}
private void mergeSortInternal(int[] array, int left, int right) {
if(left >= right - 1)
return;
int mid = (left + right) >>> 1;
mergeSortInternal(array, left, mid);
mergeSortInternal(array, mid, right);
merge(array, left, mid, right);
}
public void mergeSort(int[] array) {
for (int i = 1; i < array.length; i = i * 2) {
for (int j = 0; j < array.length; j = j + 2 * i) {
int low = j;
int mid = j + i;
if (mid >= array.length) {
continue;
}
int high = mid + i;
if (high > array.length) {
high = array.length;
}
merge(array, low, mid, high);
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。