数据结构----交换排序(冒泡排序、快速排序,C语言)

冒泡排序

时间复杂度为O(n2)

/*************冒泡排序*************/
void BubbleSort(int r[], int n)
{
	int i, j,flag,temp;
	for (i = n - 1; i >= 1; i--)
	{
		flag = 0;
		for (j = 1; j <= i; j++)
		{
			if (r[j - 1] > r[j])
			{
				temp = r[j];
				r[j] = r[j - 1];
				r[j - 1] = temp;
				flag = 1;
			}
		}
	}
	printf("冒泡排序后序列为:");
	for (int m = 0; m < n; m++)
		printf("%d ", r[m]);
}

快速排序

快速排序是对冒泡排序的一种改进

时间复杂度最坏情况下是O(n2),但一般情况下,快速排序的时间复杂度是O(nlog2n)

/***********快速排序***********/
void QuickSort(int r[],int low,int high)
{
	int i;
	if (low < high)
	{
		int pivotpos = Partition(r, low, high);
		QuickSort(r, low, pivotpos-1);
		QuickSort(r, pivotpos + 1, high);
	}
}
void Print(int r[])
{
	printf("\n快速排序后序列为:");
	for (int i = 0; i < count; i++)
		printf("%d ", r[i]);
}

//快速排序的划分操作版本
int Partition(int r[],int low,int high)
{
	int pivot = r[low];     //将当前表中第一个元素设为基准,对表进行划分
	while (low < high)
	{
		while (low < high && r[high] >= pivot)
			--high;	     
		r[low] = r[high];//将比基准小的元素移到左端
		while (low < high && r[low] <= pivot)
			++low;
		r[high] = r[low];   //将比基准大的元素移动到右端
	}
	r[low] = pivot;     //基准元素存放到最终位置
	return low;     //返回存放基准值的最终位置
}

完整版本代码

#include <stdio.h>
#define maxSize 100
int R[maxSize] = { 0 };
int count = 0;

void Indata()
{
	int i = 0;
	printf("请输入整数数据(按回车键结束输入):");
	while (1)
	{
		scanf_s("%d", &R[i]);
		i++;
		count++;
		char c = getchar();
		if ('\n' == c)
			break;
	}
}

/*************冒泡排序*************/
void BubbleSort(int r[], int n)
{
	int i, j,flag,temp;
	for (i = n - 1; i >= 1; i--)
	{
		flag = 0;
		for (j = 1; j <= i; j++)
		{
			if (r[j - 1] > r[j])
			{
				temp = r[j];
				r[j] = r[j - 1];
				r[j - 1] = temp;
				flag = 1;
			}
		}
	}
	printf("冒泡排序后序列为:");
	for (int m = 0; m < n; m++)
		printf("%d ", r[m]);
}

/***********快速排序***********/
void QuickSort(int r[],int low,int high)
{
	int i;
	if (low < high)
	{
		int pivotpos = Partition(r, low, high);
		QuickSort(r, low, pivotpos-1);
		QuickSort(r, pivotpos + 1, high);
	}
}
void Print(int r[])
{
	printf("\n快速排序后序列为:");
	for (int i = 0; i < count; i++)
		printf("%d ", r[i]);
}

//快速排序的划分操作版本
int Partition(int r[],int low,int high)
{
	int pivot = r[low];     //将当前表中第一个元素设为基准,对表进行划分
	while (low < high)
	{
		while (low < high && r[high] >= pivot)
			--high;	     
		r[low] = r[high];//将比基准小的元素移到左端
		while (low < high && r[low] <= pivot)
			++low;
		r[high] = r[low];   //将比基准大的元素移动到右端
	}
	r[low] = pivot;     //基准元素存放到最终位置
	return low;     //返回存放基准值的最终位置
}

void main()
{
	Indata();
	BubbleSort(R, count);
	QuickSort(R, 0, count-1);
	Print(R);
	system("pause");
}

结果图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值