1. 算法描述
把原始的数组分成若干的子数组,对每一个子数组进行排序;继续把子数组与子数组合并,合并后仍然有序,直到全部合并完成,形成有序的数组。
2. 算法实现
2.1. 合并子数组
/**
* @param unsorted the unsorted array
* @param first the start index for the 1st sub array
* @param mind the end index for the 1st sub array
* @param last the end index for the 2nd sub array
* @param sorted the temp array
*/
void merge(int unsorted[], int first, int mid, int last, int sorted[])
{
int i = first; // cursor for the 1st sub array.
int j = mid + 1; // cursor for the 2nd sub array
int k = 0; // cursor for the temp array
while (i <= mid && j <= last)
{
if (unsorted[i] <= unsorted[j])
{
sorted[k++] = unsorted[i++];
}else
{
sorted[k++] = unsorted[j++];
}
}
while (i <= mind)
{
sorted[k++] = unsorted[i++];
}
while (j <= last)
{
sorted[k++] = unsorted[j++];
}
for (int t = 0; t < k; t++)
{
unsorted[first + t] = sorted[t];
}
}
2.2. 递归子数组
void mergeSort(int a[], int first, int last, int temp[])
{
if (first < last)
{
int mid = (first + last) / 2;
mergeSort(a,first, mind, temp);
mergeSort(a,mid + 1, last, temp);
merge(a,first,mid,last, temp);
}
}
void Test()
{
int a[10];
int temp[10];
mergeSort(a,0,9,temp);
}