快速排序算法C语言实现

/*
 ============================================================================
 Name        : InsortDemo.c
 Author      : 董乐强
 Version     :
 Copyright   : Your copyright notice
 Description : Hello World in C, Ansi-style
 ============================================================================
 */

#include <stdio.h>
#include <stdlib.h>

typedef int ElemType;

/**
 * 交换两个数
 */
void swap(ElemType * a, ElemType * b) {
	ElemType temp = 0;
	temp = *a;
	*a = *b;
	*b = temp;
}

/**
 * 快速排序算法
 */
//快速排序核心算法
void speedSort1(int left, int right, ElemType * p) {
	if (left > right)
		return;
	int i = left;
	int j = right;
	//左边的第一个元素,作为枢轴
	int role = p[left];
	while (i != j) {
		//首先从右边往左进行扫描
		for (; i < j; j--)
			if (p[j] < role)
				break;
		//然后从左往右扫描
		for (; i < j; i++)
			if (p[i] > role)
				break;
		if (i < j)
			swap(&p[i], &p[j]);
	}
	swap(&p[left], &p[i]);
	//递归调用
	speedSort1(left, i - 1, p);
	speedSort1(i + 1, right, p);
}

void speedSort(ElemType * p, int n) {
	speedSort1(0, n - 1, p);
}

int main(void) {
	//快速排序测试
	ElemType data[] = { 5, 8, 7, 9, 9, 15, 3, 21, 8, 17 };
	speedSort(data, 10);
	int i = 0;
	for (i = 0; i < 10; i++)
		printf("%d ", data[i]);
	printf("\n");

	return EXIT_SUCCESS;
}

    原文作者:排序算法
    原文地址: https://blog.csdn.net/u011145904/article/details/77896211
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞