数据结构排序算法之交换排序

本文介绍了两种常见的交换排序算法:冒泡排序和快速排序。冒泡排序通过不断交换相邻元素实现排序,而快速排序则通过选择基准轴并分治法进行排序,效率相对更高。提供了详细的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常见交换排序有两种:冒泡排序和快速排序

1.冒泡排序
void bubbleSort(int*num,int length)
{
	int isSort = 1 ;
	int i = 0 ;
	int j = 0 ;
	
	for(i;i<length - 1;i++)
	{
		if(i>0&&isSort ==1)
		{
			break;
		}
		printf("the times is %d\n",i);
		for(j=0;j<length - i-1;j++)
		{
			if(num[j] > num[j+1])
			{
				int tep = num[j+1];
				num[j+1] =num [j];
				num[j] =tep;
				isSort = 0;
			}
		}
	}
}


2.快速排序
快速排序是基于冒泡排序的改进,大体思路就是:先通过交换的方式确定基准轴的位置,即基准轴左侧都不大于基准轴,右侧都不小于基准轴,数组基本有序。其后对左侧和右侧的子序列分别进行递归调用,直到呆排序列只有一个记录,则整个数组排序完成。
代码如下:
int partition(int *num,int left,int right)
{
	int low = left;
int high = right;
int key = num[low];
while(low < high)
{
	while(num[high] >key&&low<high)
	{
		high -=1;
	}
	num[low]=num[high];
	while(num[low] < key&&low<high)
	{
		low+=1;
	}
	num[high] = num[low];
}
num[low] = key;
return low;
}
void qSort(int*num, int low,int high)    
{    if(low < high)
   {
	 int pivotloc = partition(num,low,high);
	if(pivotloc < (low + high)/2)
	{
		qSort(num,1,pivotloc-1);
		qSort(num,pivotloc+1,high);
	}else{
		qSort(num,pivotloc+1,high);
		qSort(num,1,pivotloc-1);
	}
  }
   
}    

void quickSort(int*num,int length)
{
	qSort(num,0,length-1);
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值