【数据结构】快速排序

       快速排序是通过对序列不断划分,把原始序列以划分元素为界形成两个子序列,再对子序列重复划分的过程。这是一个递归的过程,终止条件就是最终所有的子序列都只含有一个元素

       首先需要一个数组序列,再对其进行划分(重点就是划分)。每次划分都需要设置前后两个指针(low和high),两个指针依次往中间位置移动,当指针重合时,结束这一次划分,还需要设置一个枢轴(temp)。最后的结果分三块,第一块的元素都小于第二块元素,第三块都大于第二块。所以第一次划分大概如下图:

       现在讲一下两个指针是如何将序列划分的:先是从high指针往前走,如果high指针所指向的数比枢轴(temp)大的话则继续往前走,直到碰见比枢轴小的数时将这个high指针所指向的数复值给low指针指向的位置。接着就从low指针开始往后走,当遇见比枢轴(temp)大的数就将low指针所指向的数复值给high现在指向的位置。重复以上操作,直至high和low指针指向同一个位置是停止上面的操作,但是需要将枢轴(temp)的数复值给这个位置上的数。这样就出现了三块序列。

int partition(int arr[], int low, int high)
{
	int temp = arr[low];
	while (low < high)
	{
		while (arr[high] >= temp && low < high)
		{
			high--;
		}
		if (arr[high] < temp)
		{
			arr[low] = arr[high];
			low++;
		}
		while (arr[low] <= temp && low < high)
		{
			low++;
		}
		if (arr[low] > temp)
		{
			arr[high] = arr[low];
			high--;
		}
	}
	arr[low] = temp;
	return low;
}

 

       再接下来就是重复操作,从第一块中再分三块,也需要前后指针以及枢轴。我就不再重复了,就划分好的序列画出来:

      第三块也是一样的操作 ,如下图:

void quicksort(int arr[], int low, int high)
{
	int k;
	if (low < high)
	{
		k = partition(arr, low, high);
		quicksort(arr, low, k - 1);//第一块序列
		quicksort(arr, k + 1, high);第三块序列
	}
}

 

一直重复上面操作,直至出现 :

       这就是就是快速排序的所有步骤。

       现在我把从头到尾的代码发出来:

#include <stdio.h>
#include <stdlib.h>
int partition(int arr[], int low, int high)
{
	int temp = arr[low];
	while (low < high)
	{
		while (arr[high] >= temp && low < high)
		{
			high--;
		}
		if (arr[high] < temp)
		{
			arr[low] = arr[high];
			low++;
		}
		while (arr[low] <= temp && low < high)
		{
			low++;
		}
		if (arr[low] > temp)
		{
			arr[high] = arr[low];
			high--;
		}
	}
	arr[low] = temp;
	return low;
}


void quicksort(int arr[], int low, int high)
{
	int k;
	if (low < high)
	{
		k = partition(arr, low, high);
		quicksort(arr, low, k - 1);
		quicksort(arr, k + 1, high);
	}
}

int main()
{
	int arr[] = { 52,49,80,36,14,58,61,97,23,75 };//想要一个一个敲进去就用for循环
	int low = 0;
	int high = 9;
	printf("排序后的顺序:\n");
	quicksort(arr, low, high);
	for (int i = 0; i <= 9; i++)
	{
		printf("%d ", arr[i]);
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值