递归方式实现简单的快速排序

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40818798/article/details/86515966

快速排序: 一种广受程序猿们追捧的排序算法。其基本思想为:选定一个基准值,然后以此基准值为中间枢纽,将列表中各元素划分到两个区间去——大于枢纽值的区间和小于枢纽值的区间。在两区间内再选取各自新的枢纽值,划分成新的区间,直到每个区间都只有一个元素为止,排序完成。

def quicksort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0]
        less = [i for i in array[1:] if i <= pivot]
        greater = [i for i in array[1:] if i > pivot]
        return quicksort(less) + [pivot] + quicksort(greater)

print quicksort([10, 5, 2, 3])
#include <stdio.h>

#define MAX 100
typedef  struct
{
	int element[MAX];
	int length;
}Queue;

void swap(Queue *L, int i, int j)
{
	int temp = L->element[i];
	L->element[i] = L->element[j];
	L->element[j] = temp;
}

int FindKey(Queue *L, int low, int high)
{
	int PKey;
	PKey = L->element[low];
	while (low < high)
	{
		while (low < high && L->element[high] >= PKey)
		{
			high--;
		}
		swap(L, low, high);
		while (low < high && L->element[low] <= PKey)
		{
			low++;
		}
		swap(L, low, high);
	}
	return low;
}
void Qsort(Queue *L, int low, int high)
{
	int key;
	if (low < high)
	{
		key = FindKey(L,low,high);
		Qsort(L, low, key - 1);
		Qsort(L, key + 1, high);
	}
}

void QuickSort(Queue *L)
{
	Qsort(L,0,L->length);
}
void Print(Queue L)
{
	for (int i = 0; i < L.length; i++)
	{
		printf("%d  ", L.element[i]);
	}
}
int main()
{
	Queue L;
	int d[MAX] = { 50,10,90,30,70,40,80,60,20 };
	for (int i = 0; i < 9; i++)
	{
		L.element[i] = d[i];
	}
	L.length = 8;
	QuickSort(&L);
	Print(L);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40818798/article/details/86515966
今日推荐