码迷,mamicode.com
首页 > 编程语言 > 详细

看数据结构写代码(64) 归并排序

时间:2015-05-03 13:24:19      阅读:151      评论:0      收藏:0      [点我收藏+]

标签:归并排序   归并排序c语言秒速   

参考网址:http://blog.csdn.net/morewindows/article/details/6678165

// MergeSort.cpp : 定义控制台应用程序的入口点。
//归并排序

#include "stdafx.h"
#include <cstdlib>

//合并两个有序数组
void mergeArray(int * array,int first,int mid,int last,int * temp){
	int i = first;
	int j = mid + 1;
	int k = first;
	while (i <= mid && j <= last){
		if (array[i] < array[j]){
			temp[k++] = array[i++];
		}
		else{
			temp[k++] = array[j++];
		}
	}
	//将剩余部分插入 
	while (i <= mid){
		temp[k++] = array[i++];
	}
	while (j <= last){
		temp[k++] = array[j++];
	}
	//让array 数组 部分有序
	for (int i = first; i <= last; i++){
		array[i] = temp[i];
	}
}

void merge(int * array,int first,int last,int * temp){
	if (last > first){
		int mid = (first + last) / 2;
		merge(array,first,mid,temp);//前半部分有序
		merge(array,mid+1,last,temp);//右半部分有序..
		mergeArray(array,first,mid,last,temp);
	}
}

void mergeSort(int * array,int num){
	int * tempArray = (int *) malloc(sizeof(int) * num);
	merge(array,0,num-1,tempArray);
	free(tempArray);
}

static int testArray[] = {33,22,99,77,66,44,55,88,11,100};

int _tmain(int argc, _TCHAR* argv[])
{
	mergeSort(testArray,10);
	for (int i = 0; i < 10; i++){
		printf("%d\t",testArray[i]);
	}
	return 0;
}


看数据结构写代码(64) 归并排序

标签:归并排序   归并排序c语言秒速   

原文地址:http://blog.csdn.net/fuming0210sc/article/details/45457977

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!