_数据结构_快速排序

快速排序是一种二叉树结构的交换排序算法

    其基本思想是在序列中找一个元素作为基准值,将排序集合分割为两个子序列,左子序列中的所有元素都小于基准值,右子序列中的所有元素均大于基准值,再将左右子树重复此操作,知道所有元素都排列在相应位置

源代码获取:
https://github.com/akh5/C-/blob/master/%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84/%E6%8E%92%E5%BA%8F/quicksort.c

讨论前后指针法

序列中分别在前后定义两个指针,将一开始开头指针指向的值作为基准值, 后指针开始向前遍历,遍历到比基准值小的值时,当前位置的值与基准值交换, 前指针开始向后遍历,遇到比基准值大的值时,当前位置与基准值交换,换前指针向前遍历,反复交替,直到前指针与后指针交叉。

在这里插入图片描述
此时将序列分为左右两个子树,基准值为根,左子树均小于基准值,右子树均大于基准值
在这里插入图片描述

#include <stdio.h>

void Swap(int*a, int* b)  //交换的函数
{
	int temp;
	temp = *a;
	*a = *b;
	*b = temp;
}

void dealsort(int *arr, int start, int end) 
{
	if (start >= end)
	{
		return;
	}

	int flag = 1;
	int i = start, j = end;
	while (i<j)
	{
		if (arr[i] > arr[j])
		{
			Swap(arr[i], arr[j]);
			flag = !flag;
		}
		if (flag == 1)
		{
			j--;
		}
		else
		{
			i++;
		}
	}
	dealsort(arr, start, i - 1);
	dealsort(arr, i + 1, end);
}

通过递归操作完成二叉树创建。递归出口设置为 前指针>=后指针时。flag用于前后指针遍历操作的转换,每次交换后flag取反,就可以实现前后指针交替遍历

发布了52 篇原创文章 · 获赞 13 · 访问量 5442

猜你喜欢

转载自blog.csdn.net/MPF1230/article/details/104076960