package Utils.Sort;
/**
*歸並排序,要求待排序的數組必須實現Comparable接口
*/
public class MergeSort implements SortStrategy
{ private Comparable[] bridge;
/**
*利用歸並排序算法對數組obj進行排序
*/
public void sort(Comparable[] obj)
{ if (obj == null)
{ throw new NullPointerException("The param can not be null!");
}
bridge = new Comparable[obj.length]; //初始化中間數組
mergeSort(obj, 0, obj.length - 1); //歸並排序
bridge = null;
}
/**
*將下標從left到right的數組進行歸並排序
*@param obj 要排序的數組的句柄
*@param left 要排序的數組的第一個元素下標
*@param right 要排序的數組的最後一個元素的下標
*/
private void mergeSort(Comparable[] obj, int left, int right)
{ if (left < right)
{ int center = (left + right)/2;
mergeSort(obj, left, center);
mergeSort(obj, center + 1, right);
merge(obj, left, center, right);
}
}
/**
*將兩個對象數組進行歸並,並使歸並後為升序。歸並前兩個數組分別有序
*@param obj 對象數組的句柄
*@param left 左數組的第一個元素的下標
*@param center 左數組的最後一個元素的下標
*@param right 右數組的最後一個元素的下標
*/
private void merge(Comparable[] obj, int left, int center, int right)
{ int mid = center + 1;
int third = left;
int tmp = left;
while (left <= center && mid <= right)
{ //從兩個數組中取出小的放入中間數組
if (obj[left].compareTo(obj[mid]) <= 0)
{ bridge[third++] = obj[left++];
} else
bridge[third++] = obj[mid++];
}
//剩余部分依次置入中間數組
while (mid <= right)
{ bridge[third++] = obj[mid++];
}
while (left <= center)
{ bridge[third++] = obj[left++];
}
//將中間數組的內容拷貝回原數組
copy(obj, tmp, right);
}
/**
*將中間數組bridge中的內容拷貝到原數組中
*@param obj 原數組的句柄
*@param left 要拷貝的第一個元素的下標
*@param right 要拷貝的最後一個元素的下標
*/
private void copy(Comparable[] obj, int left, int right)
{ while (left <= right)
{ obj[left] = bridge[left];
left++;
} }
}