数据结构----快速排序程序例子(c语言)

快速排序方法之一

       先找到第一个元素的位置,将数据分为两部分,然后通过递归调用实现

例子程序

#include <stdio.h>

void QuickSort(int *a, int low, int high);
int FindPos(int *a, int low, int high);
int main(void)
{
	int a[6] = {2,1,0,5,4,3};
	int i;

	QuickSort(a,0,5); //0 第一个元素下标  5最后一个元素下标
	for(i=0; i<6;++i)
		printf("%d ",a[i]);
	printf("\n");

	return 0;
}

void QuickSort(int *a, int low, int high)
{
	int pos;
	if(low < high)
	{
		pos = FindPos(a,low,high);
		QuickSort(a,low,pos-1);	
		QuickSort(a,pos+1,high);
	}

	return ;
}
int FindPos(int *a, int low, int high)
{
	int val = a[low];
	while(low < high)
	{
		while (low < high && a[high] >= val)
			--high;
		a[low] = a[high];
		while (low < high && a[low] <= val)
			++low;
		a[high] = a[low];
	}
	
	a[low] = val;

	return high;//low == high
}

编译

gcc quicksort.c -o quicksort

结果测试

test# ./quicksort 
0 1 2 3 4 5 

Guess you like

Origin blog.csdn.net/wgl307293845/article/details/121318973