歸併排序


分治法的典型排序 左右分別分割再排序合併 以達到排序的目的


---C語言實現

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>

//遍歷數組
void LoopForArr(int arr[],int length)
{
	int count;
	if(arr == NULL || length <=0)return ;
	for(count = 0;count<length;count++)
	{
		printf("%d  ",arr[count]);
	}
	printf("\n");
}

//合併
void MergerAndSort(int arr[],int low,int mid,int high,int TempArr[])
{
	int Left = low;
	int Right = mid+1;
	int count = low;
	while(Left<=mid && Right<=high)
	{
		TempArr[low++] = arr[Left] <arr[Right]?arr[Left]:arr[Right];
		arr[Left] <arr[Right]?Left++:Right++;
	}

	while(Left<=mid)
		TempArr[low++] = arr[Left++];
	while(Right<=high)
			TempArr[low++] = arr[Right++];

	for(count;count<=high;count++)
	{
		arr[count] = TempArr[count];
	}
}

//歸併過程
void SeprateAndmerger(int arr[],int low,int high,int TempArr[])
{
	int mid;

	if(low<high)
	{
		mid = (low+high)/2;
		SeprateAndmerger(arr,low,mid,TempArr);
		SeprateAndmerger(arr,mid+1,high,TempArr);
		MergerAndSort(arr,low,mid,high,TempArr);
	}
}

//歸併排序
void MergerSort(int arr[],int length)
{
	int low;
	int high;
	
	int *TempArr = NULL;
	if(arr == NULL || length <=0)return ;

	low = 0;
	high = length-1;
	TempArr = (int *)malloc(sizeof(int)*length);
	memset(TempArr,0,sizeof(int)*length);

	SeprateAndmerger(arr,low,high,TempArr);
	free(TempArr);
	TempArr = NULL;
}

int main()
{
	int arr[] = {22,34,1,6,9,123,55,78,12,4,56,87,52};
	MergerSort(arr,sizeof(arr)/sizeof(arr[0]));
	LoopForArr(arr,sizeof(arr)/sizeof(arr[0]));
	system("pause");
	return 0;
}

發佈了49 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章