1. 程式人生 > >快速排序-堆排序-歸併排序

快速排序-堆排序-歸併排序

#include "stdafx.h"
#include <iostream>
using namespace std;

template <typename T>
void QuickSort(T *arr, int start, int end)
{
	if (start >= end) 
		return;
	int left = start;
	int right = end;
	T num = arr[start];
	
	while (left < right)
	{
		while (arr[right] > num) 
			right--;
		if (left < right) 
			arr[left++] = arr[right];
		while (arr[left] < num) 
			left++;
		if (left < right) 
			arr[right--] = arr[left];
	}
	arr[left] = num;

	QuickSort(arr, start,left-1);
	QuickSort(arr, left+1, end);
}
void MergeSortQuick(int *arr,int start, int num, int end, int *temp)
{
	int i = start;
	int j = num+1;

	int k = 0;
	while(i <= num && j <= end) 
	{
		if(arr[i] <= arr[j]) 
			temp[k++] = arr[i++];
		else
			temp[k++] = arr[j++];
	}

	while (i <= num) 
		temp[k++] = arr[i++];
	while (j <= end) 
		temp[k++] = arr[j++];
	for(i = 0; i < k; i++)
		arr[start+i] = temp[i];
}
void MergeSort(int *arr, int start, int end, int *temp)
{
	if (start < end) 
	{
		int n = (start + end) / 2;
		MergeSort(arr,start,n,temp);
		MergeSort(arr, n+1, end, temp);
		MergeSortQuick(arr,start, n, end, temp);
	}
}

void swaps(int *nums, int m, int n)
{
    int tmp = nums[m];  
    nums[m] = nums[n];  
    nums[n] = tmp;  
}

void MaxHeap(int *arr, int start, int end)
{
	int sNode = start;
	int fNode = start*2+1;

	while (fNode <= end) 
	{
		if (fNode+1 <= end && arr[fNode] < arr[fNode+1]) 
			fNode++;
		if (arr[sNode] > arr[fNode]) 
			return;
		else
		{
			swaps(arr, sNode, fNode);
			sNode = fNode;
			fNode = 2*sNode+1;
		}
		
	}
}
void HeapSort(int *arr, int leng)
{
	for(int i = leng/2 + 1; i >= 0; i--)
	{
		MaxHeap(arr, i, leng-1);//構建大頂堆
	}

	for(int j = leng-1; j >= 0; j--)
	{
		swaps(arr,0, j);
		MaxHeap(arr,0,j-1);
	}


}
void sort(int *arr, int leng)
{
	//快速排序
	QuickSort(arr,0,leng-1);

	//歸併排序
	int *temp = new int[leng];
	if (temp) {
		MergeSort(arr, 0, leng-1, temp);
	}
	
	//堆排序
	HeapSort(arr,leng);

}
int main(int argc, char* argv[])
{
	int arr[9] = {1,7,3,4,12,345,2,8,9};
	sort(arr,9);
	for(int i = 0; i < 9; i++)
		cout << arr[i]<< endl;
	cin.get();
	return 0;
}