数据结构书上可运行代码-快排

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <map>
#include <algorithm>
using namespace std;

int Partition(int L[],int low,int high)
{
    int pivotkey = L[low];
    int i = low;
    int j = high;
    while (i<j)
    {
        while (i<j && L[j] >= pivotkey)
            j--;
        L[i] = L[j];
        while (i<j && L[i] <= pivotkey)
            i++;
        L[j] = L[i];
    }
    L[i] = pivotkey;
    return i;
}//Partition
void QSort(int L[], int low, int high)
{
//对L.r[low]~L.r[high]的元素进行快速排序
    if (low < high)
    {
        int pivotloc = Partition(L,low,high); //一趟划分
        QSort(L,low,pivotloc - 1);
        QSort(L, pivotloc+1,high);
    }//if
} //QSort
int main()
{
    int a[100100];
	int n, m;
	while (~scanf("%d", &n))
	{
		for (int i = 0; i < n; i++)
			scanf("%d", &a[i]);
		Partition(a, 0, n - 1);
		for (int i = 0; i < n; i++)//输出一趟快排;
		{
			if (i == n - 1) printf("%d\n", a[i]);
			else printf("%d ", a[i]);
		}
		QSort(a, 0, n - 1);
		for (int i = 0; i < n; i++)
		{
			if (i == n - 1) printf("%d\n", a[i]);
			else printf("%d ", a[i]);
		}
	}
	return 0;
}

/*

8
49 38 65 97 76 13 27 49


*/

猜你喜欢

转载自blog.csdn.net/weixin_42137874/article/details/110405870
今日推荐