您好,登錄后才能下訂單哦!
將數組分為2塊,再到每一小塊再分為兩塊,直到最后一個元素為一塊,然后進行有序數組合并,最終合并為一個有序數組
代碼實現
public static void mergeSorts ( int[] array){
mergeSortsInternal(array,0,array.length)
//mergeSortsInternalNoR(array);
}
/**
* 歸并排序:遞歸內部排序
*/
public static void mergeSortInternal ( int[] array, int low, int high){
if (low + 1 >= high) {//[low,high)
return;
}
int mid = (low + high) / 2;
mergeSortInternal(array, low, mid);
mergeSortInternal(array, mid, high);
merge(array, low, mid, high);
}
private static void merge ( int[] array, int low, int mid, int high){
int length = high - low;
int[] extral = new int[length];
//[low,mid]
//[mid,high]
int less = low;
int great = mid;
int i = 0;
while (less < mid && great < high) {
if (array[less] <= array[great]) {
extral[i] = array[less];
less++;
i++;
} else {
extral[i] = array[great];
great++;
i++;
}
}
while (less < mid) {
extral[i++] = array[less++];
}
while (great < high) {
extral[i++] = array[great++];
}
for (int j = 0; j < length; j++) {
array[low + j] = extral[j];
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。