排序算法C++实现

#include <iostream>
#include <windows.h>
using namespace std;

#define MERGE_SORT

void BubbleSort(int a[], int n)
{
	for (int i=n-1;i>0;i--)
	{
		for (int j=0;j<i;j++)
		{
			if (a[j]>a[j+1])
				swap(a[j],a[j+1]);
		}
	}
}

void InsertSort(int a[], int n)
{
	for (int i=1;i<n;i++)
	{
		int j=i-1;
		int temp=a[i];
		while (j>=0&&a[j]>temp)
		{
			a[j+1]=a[j];
			j--;
		}
		a[j+1]=temp;
	}
}

void SeleteSort(int a[], int n)
{
	for (int i=n-1;i>0;i--)
	{
		int max=i;
		for (int j=0;j<i;j++)
		{
			if (a[j]>a[max])	
				max=j;	
		}
		swap(a[max],a[i]);
	}
}

void QuickSort(int a[], int left, int right)
{
	if (left<right)
	{
		int i=left, j=right, temp=a[i];
		while (i<j)
		{
			while (i<j&&a[j]>=temp)
				j--;
			if (i<j)
				a[i++]=a[j];
			while (i<j&&a[i]<=temp)
				i++;
			if (i<j)
				a[j--]=a[i];						
		}
		a[i]=temp;
		QuickSort(a,left,i-1);
		QuickSort(a,i+1,right);
	}
}

void ShellSort(int a[], int n)
{
	int i,j,gap;
	for (gap=n/2;gap>0;gap/=2)
	{
		for (i=0;i<gap;i++)
		{
			for (j=i+gap;j<n;j+=gap)
			{
				if (a[j-gap]>a[j])
				{
					int k=j-gap;
					int temp=a[j];
					while (k>=0&&a[k]>temp)
					{
						a[k+gap]=a[k];
						k-=gap;
					}
					a[k+gap]=temp;
				}
			}
		}
	}
}

#ifdef MERGE_SORT

void MergeArray(int a[],int start, int mid, int end, int temp[])
{
	int i=start, j=mid+1;
	int m=mid, n=end;
	int k=0;
	while (i<=m&&j<=n)
	{
		if (a[i]>=a[j])
			temp[k++]=a[j++];
		else
			temp[k++]=a[i++];
	}
	while (i<=m)
		temp[k++]=a[i++];
	while (j<=end)
		temp[k++]=a[j++];
	for (i=0;i<k;i++)
		a[i+start]=temp[i];
}

void IMergeSort(int a[],int start, int end, int temp[])
{
	if (start<end)
	{
		int mid=(start+end)/2;
		IMergeSort(a,start,mid,temp);
		IMergeSort(a,mid+1,end,temp);
		MergeArray(a,start,mid,end,temp);
	}

}

bool MergeSort(int a[], int n)
{
	int* temp=new int[n];
	if (!temp)
		return false;
	IMergeSort(a,0,n-1,temp);
	delete[] temp;
	return true;
}
#endif

void HeapSort(int a[], int n)
{

}

void main()
{
	int a[10]={7,3,9,0,1,8,2,4,6,5};
	//BubbleSort(a,10);
	//InsertSort(a,10);
	//SeleteSort(a,10);
	//QuickSort(a,0,9);
	//ShellSort(a,10);
	MergeSort(a,10);
	for (int i=0;i<10;i++)
		cout<<a[i]<<"  ";
	cout<<endl;
	system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值