几种常见排序算法的实现(冒泡法,选择法,插入法,快速排序、堆排序)

#include "stdafx.h"

//in the i th round ordering, j always points to the max element so far
void bubble_sort(int *a, int len)
{
	for(int i=0; i<len-1; i++)
	{
		for(int j=0; j<len-1-i; j++)
		{
			if(a[j]>a[j+1])
			{
				swap<int>(a[j],a[j+1]);
			}
		}
	}
}

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

/*in the i th round ordering, k always points to the min element so far. the additional
variable k gives it a chance to make the swap till a whole round ordering is finished.
so this algorithm should have less sawp operatons than bubble sort.
*/
void select_sort(int *a, int len)
{
	int k;
	for (int i=0; i<len-1; i++)
	{
		k=i;
		for(int j=len-1; j>i; j--)
		{
			if(a[k]>a[j]) k = j;
		}
		if(k!=i)
		{
			swap<int>(a[k], a[i]);
		}
	}
}

// every round ordering, we choose the first element as benchmark.
void quick_sort_recursion(int *a, int low, int high)
{
	int bench=a[low];
	int end=high;
	while(low<high)
	{
		while(low<high && a[high]>=bench) high--;
		a[low]=a[high];
		while(low<high && a[low]<=bench) low++;
		a[high]=a[low];
	}
	a[low]=bench;//now position low should equal to position high
	if(low>1) // there are at least two elements before position low
	{
		quick_sort_recursion(a, 0, low-1);
	}
	if(low+1<end) // there are at least two elements after position low
	{
		quick_sort_recursion(a, low+1, end);
	}
}

void quick_sort(int *a, int len)
{
	quick_sort_recursion(a, 0, len-1);
}

//every round ordering, we want to insert a[i] to correct postion in an ordered array p[0]-p[i-1]
//we compare a[i] with ordered array p[0]-p[i-1] from back, if a[i] is smaller, than move p[j] to p[j+1]
//else insert a[i] to p[j+1]
void insert_sort(int *a, int len)
{
	int *p = new int[len];
	int i,j;
	for(i=0; i<len; i++)
	{
		for(j=i-1; j>=0; j--)
		{
			if(a[i]<p[j])
			{
				p[j+1] = p[j];
			}
			else 
			{
				break;
			}
		}
		p[j+1] = a[i];
	}
	copy(p, p+len, a);
	delete [] p;
}

// 堆排序
// 对堆a[m, n]建大顶堆
void heap_adjust(int *a, int m, int n)
{
	int rc = a[m];
	for(int j=2*m; j<=n; j*=2)
	{
		if(j+1<=n && a[j+1]>a[j])
		{
			j++;//如果右节点非空且较大,则取右节点
		}
		if(rc>=a[j])
		{
			break;//构建大顶堆完毕
		}
		else
		{
			a[m] = a[j];//调整堆
			m = j;//记录空位
		}
	}
	a[m] = rc;
}

void heap_sort(int *a, int len)
{
	for (int i=(len/2)-1; i>=0; i--)//构建大顶堆
	{
		heap_adjust(a, i, len-1);
	}
	for (int i=len-1; i>0; i--)
	{
		swap<int>(a[0], a[i]);//交换堆顶元素与最后一个元素,得到此轮排序最大值
		heap_adjust(a, 0, i-1);//对新的堆a[0, i-1]重新构建大顶堆
	}
}

你可能感兴趣的:(几种常见排序算法的实现(冒泡法,选择法,插入法,快速排序、堆排序))