2.1 插入排序
示例C代码------>>>>>>>
void InSert(int a[], int len)
{
int i, j;
for(i = 2; i< len; i++)
{
if(a[i] <a[i-1])
{
a[0] = a[i];
j = i-1;
do{
a[j+1] = a[j];
j--;
}while(a[0] < a[j]);
a[j+1] = a[0];
}
}
}
2.3 设计算法 ------>>分治法<<-----------
归并算法关键是合并步骤中两个已排序序列的合并,为了避免在每个基本步骤必需检查是否有堆为空,在每个堆的底部放置一张哨兵牌,它包含一个特殊的值,这里用无穷大OO表示,起码要大于要排序数组中的最大值。C代码如下
void MergePass(int a[], int low, int d, int high)
{
int n1, n2;
int *L, *R;
int i, j, k;
n1 = d - low + 1;
n2 = high - d;
L = (int *)malloc((n1+1) * sizeof(int));
if(!L)
exit(1);
R = (int *)malloc((n2+1) * sizeof(int));
if(!R)
exit(1);
for(i = 0; i < n1; i++)
L[i] = a[low+i];
for(i = 0; i < n2; i++)
R[i] = a[d+1+i];
L[n1] = 100000;//这里的值要大于排序数组中的最大值
R[n2] = 100000;
i = 0;
j = 0;
for(k = low; k <= high; k++)
{
if(L[i] <= R[j])
a[k] = L[i++];
else
a[k] = R[j++];
}
free(L);
free(R);
}
void MergeSort(int a[], int low, int high)
{
int mid;
if(low < high)
{
mid = (low+high) / 2;
MergeSort(a, low, mid);
MergeSort(a, mid+1, high);
MergePass(a, low, mid, high);
}
}
归并排序运行时间(nlg(n)),优于插入排序的(n^2)