给你一个归并排序的具体算法和分析:
两路归并排序算法思路:
①.
把n个记录看成n个长度为l的有序子表
;
②.
进行两两归并使记录关键字有序,得到n/2个长度为2的有序子表;
③.
重复第②步直到所有记录归并成一个长度为n的有序表为止;
具体算法:
//
归并操作
template
static
void
merge
(typearray[],
int
p,
int
q,
int
r){
int
i
,
k
;
int
begin1
,
end1
,
begin2
,
end2
;
int*
temp
=
(int*)malloc((r-p)*sizeof(int))
;
begin1
=
p
;
end1
=
q
;
begin2
=
q+1
;
end2
=
r
;
k
=
0
;
while
(begin1
<=
end1
&&
begin2
<=
end2){
if
(array[begin1]
<
array[begin2]){
temp[k]
=
array[begin1]
;
begin1
++
;
}
else{
temp[k]
=
array[begin2]
;
begin2
++
;
}
k
++
;
}
while
(begin1
<
end1)
temp[k++]
=
array[begin1++]
;
while
(begin2
<
end2)
temp[k++]
=
array[begin2++]
;
for
(i
=
0
;
i
<
(r-p)
;
i
++)
array[p+i]
=
temp
;
free(temp)
;
}
//--------------------------------------------------------------------------------
template
void
mergesort(typearray[],
unsigned
int
first,
unsigned
int
last){
int
mid
=
0
;
if
(first
<
last)
{
mid
=
(first+last)/2
;
mergesort
(array,
first,
mid)
;
mergesort
(array,
mid+1,
last)
;
merge
(array,
first,
mid,
last)
;
}
}
选择排序
#include
#define N 5
void SelectSort(int a[])
{
int temp;
int j;
for(int i=0;i
j=i;
for(int k=i+1;k
{
temp=a[j];
a[j]=a[i];
a[i]=temp;
}
}
}
void main()
{
int a[N];
printf("请输入5个整型数字:");
for(int i=0;i
SelectSort(a);
for(i=0;i
}
选择排序:
nt j;
int index;
int temp;
for (i=1; i<10; i++) //对n个记录进行n-1趟简单选择排序
{
index=i;
for (j=i+1; j<11; j++) //在无序区中选取最小记录
if (num[j]
if (index!=i)
{
temp=num[i];
num[i]=num[index];
num[index]=temp;
}
}
for(i=1;i<11;i++)
printf("%d ",num[i]);
printf("\n");
归并排序:
#include
#define LEN 8
int a[LEN] = { 5, 2, 4, 7, 1, 3, 2, 6 };
void merge(int start, int mid, int end)
{
int n1 = mid - start + 1;
int n2 = end - mid;
int left[n1], right[n2];
int i, j, k;
for (i = 0; i < n1; i++) /* left holds a[start..mid] */
left[i] = a[start+i];
for (j = 0; j < n2; ++j) /* right holds a[mid+1..end] */
right[j] = a[mid+1+j];
i = j = 0;
for (k = start; i < n1 && j < n2; ++k) {
if (left[i] < right[j]) {
a[k] = left[i];
++i;
} else {
a[k] = right[j];
++j;
}
}
if (i < n1) /* left[] is not exhausted */
for (; i < n1; i++) {
a[k] = left[i];
++k;
}
if (j < n2) /* right[] is not exhausted */
for (; j < n2; ++j) {
a[k] = right[j];
++k;
}
}
void sort(int start, int end)
{
int mid;
if (start < end) {
mid = (start + end) / 2;
printf("sort (%d-%d, %d-%d) %d %d %d %d %d %d %d %d\n",
start, mid, mid+1, end,
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
sort(start, mid);
sort(mid + 1, end);
merge(start, mid, end);
printf("merge (%d-%d, %d-%d) to %d %d %d %d %d %d %d %d\n",
start, mid, mid+1, end,
a[0], a[1], a[2], a[3], a[4], a[5], a[6], a[7]);
}
}
int main(void)
{
sort(0, LEN-1);
return 0;
}