分治法排序

#include<stdio.h>
#include<stdlib.h>
#define temp 10
int a[temp];
int b[temp]={3,6,2,9,1,4,7,8,0,13};
void merge(int low,int mid,int high)
{
	int i = low,j = mid+1,k = 0;

	while(i<=mid && j<=high)
	{
		if (b[i] <= b[j])
		{
			a[k] = b[i];

			i++;
		}
		else
		{
			a[k] = b[j];

			j++;
		}
		k++;
	}
	while (i<=mid)
	{
		a[k]=b[i];

		i++;k++;
	}
	while (j<=high)
	{
		a[k]=b[j];

		j++;k++;
	}
	for (i = 0; i < k; i++)
        b[low + i] = a[i];

}
int msort(int low,int high)
{
	int mid;
	if(low<high)
	{
		mid = (low + high)/2;
		msort(low,mid);
		msort(mid+1,high);
        merge(low,mid,high);
	}
	return 0;
}
int main()
{
    int s;
	msort(0,temp-1);
  	for(s = 0;s<temp;s++)
	{
		printf("%d ",a[s]);

	}
	printf("\n");
	return 0;
}


这是修改完之后的,因为是第一次写,难免会有差错和失误,以后一定要注意

以下是我第一次照老师上课时的板书写成的,可以发现有很多错误

#include<stdio.h>
#include<stdlib.h>
int a[6];
int b[6]={3,7,6,5,4,8};

void merge(int low,int mid,int high)
{
	int i = 0,j = mid+1,k = 0;  //i初始赋值有问题,原因是没有理解这个排序的过程

	while(i<=mid &&j<=high)
	{
		if (b[i] < b[j])
		{
			a[k] = b[i];
			i++;
		}
		else
		{
			a[k] = b[j];
			j++;
		}
		k++;
	while (i<=mid)
	{
		a[i]=b[i];
		i++;k++;
	}
	while (j<=mid)
	{
		a[j]=b[k];
		j++;k++;
	}
}
}
void msort(int low,int high) //这段程序是全放赵老师的,才开始写时没有很好的在脑子里模拟一下过程。同时我觉得也显示出了迭代算法理解起来比较复杂
{
	int mid;
	if(low<high)
	{
		mid = (low + high)/2;
		msort(low,mid);
		msort(mid+1,high);
		merge(low,mid,high);
	}
}
int main()
{
	int i;
	msort(0,5);
  	for(i = 0;i<6;i++)
	{
		printf("%d ",a[i]);
		printf("\n");
	}
	system("pause");
	return 0;
}


点赞