insertSort,quickSort,mergeSort

http://blog.csdn.net/onlyou2030/article/details/48108573已经包含了插入排序。

下面是STL排序实现,省去了边界判断,在大量数据的情况下,影响是可观的。

当然时间复杂度:O(n^2)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int * copy_backward(int * first,int* last,int* result)
{
	while (last != first) *(--result) = *(--last);
	return result;
}

void insertSort(int *first, int *last)
{
	for (int *i = first + 1; i != last; ++i)
	{
		int value = *i;
		if (value < *first)     //如果小于第一个,直接放到第一个
		{
			copy_backward(first, i, i + 1);
			*first = value;
		}
		else
		{
			int *next = i;
			--next;
			while (value < *next)
			{
				*i = *next;  //往后移数据
				i = next;
				--next;
			}
			*i = value;
		}
	}
}
int main()
{
	int a[] = { 3, 4, 5, 7, 9, 2, 10, 1, 8, 0 };
	insertSort(a, a + 10);  //[a,a+10)
	for (int i = 0; i < 10; ++i)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}


下面是STL的快速排序,省去了边界判断。

时间复杂度:O(nlgn)

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int median(int a, int b, int c)
{
	if (a < b)
		if (b < c) return b;
		else if (a < c) return c;
		else return a;
	else if (a < c) return a;
	else if (b < c) return c;
	else return b;
}

int *partition(int *first, int *last, int pivot)  
{
	while (1)  //当first>=last时,跳出循环
	{
		while (*first < pivot) ++first;
		--last;           //默认是不包括last的,需要--才对应最后一个元素
		while (*last > pivot) --last;
		if (first >= last) return first;    //返回值是分割后的右段的第一个位置
		swap(*first,*last);             //晕,不能像迭代器那样swap(first,last)
		++first;    //为什么不--last呢,因为前面有--last啊
	}
}

void quickSort(int *first, int *last)
{
	if (first == last || first == last - 1) return;
	int pivot = median(*first,*(last-1),*((first+(last-first)/2)));
	int *cut = partition(first,last,pivot);
	quickSort(first,cut);
	quickSort(cut,last);
}

int main()
{
	int a[] = { 3, 4, 5, 7, 9, 2, 10, 1, 8, 0 };
	quickSort(a, a + 10);  //[a,a+10)
	for (int *i = a; i < a+10; ++i)
		cout << *i << " ";
	cout << endl;
	return 0;
}

下面附上归并排序:

时间复杂度:O(nlgn)

优点:实现简单,概念简单

缺点:merge过程需要额外的内存。(其实现过程略)

void mergeSort(int *first, int *last)
{
	if (first == last || first == last - 1) return;
	int *mid = first + (last - first) / 2;
	mergeSort(first, mid);
	mergeSort(mid, last);
	merge(first,mid,last);
}


注:上面的方法都用到两个指针,为我们的解带来较大的优化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值