常用排序算法整理

1. 冒泡排序:

void bubble_sort(int s[], int len)
{
	int i,j,temp;
	for (i=0;i<len;i++)
		for(j=i;j<len;j++)
		if(s[i] > s[j])
		{
			temp = s[i];s[i] = s[j]; s[j] = temp;
		}
}

2. 插入排序:

void insert_sort(int s[], int len)
{
	int i,j,temp;
	for (i=1;i<len;i++)
	{
		temp = s[i];
		for(j=i-1;j>=0 && s[j]>temp;j--)
			s[j+1] = s[j];

	s[j+1] = temp;
	}
}

3.快速排序:

采用分治法,先选取一个数pivot,把小于pivot的数移到它的左边,大于pivot的数移到它的右边,然后进行递归调用

int partition(int s[],int low,int high)
{
	int pivot = s[low];
		while (low<high)
		{		
			while (low<high && s[high]>=pivot)//必须加等号,处理相等的情况
				high--;
				s[low] = s[high];
			while (low<high && s[low]<pivot)
				low++;
				s[high] = s[low];
		}
		s[low] = pivot;
		return low;
}

void quick_sort(int s[], int low, int high)
{
	int pos;
	if (low<high)
	{
		pos = partition(s,low,high);
		quick_sort(s,low,pos-1);
		quick_sort(s,pos+1,high);
	}
}

4.归并排序

也是采用分治法

void merge(int a[], int first, int mid, int last, int temp[])
{
	int i = first, j = mid + 1;
	int m = mid,   n = last;
	int k = 0;

	while (i <= m && j <= n)
	{
		if (a[i] <= a[j])
			temp[k++] = a[i++];
		else
			temp[k++] = a[j++];
	}

	while (i <= m)
		temp[k++] = a[i++];

	while (j <= n)
		temp[k++] = a[j++];

	for (i = 0; i < k; i++)
		a[first + i] = temp[i];
}

void merge_sort(int a[], int first, int last, int temp[])
{
	if(first < last)
	{
		int mid = (first + last) / 2;
		merge_sort(a, first, mid, temp);
		merge_sort(a, mid + 1, last, temp);
		merge(a, first, mid, last, temp);
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值