快速排序

来源:互联网 发布:nat穿越java实现 编辑:程序博客网 时间:2024/06/13 18:42

快速排序

flyfish

#include "stdafx.h"#include <iostream>using namespace std;void Exchange(int &a, int &b){    int t = a;    a = b;    b = t;}int Partition(int A[], int p, int r){    int t = A[r];//pivot element(主元,基准元素), 分为两部分,左侧都是小于t的,右侧都是大于t的    int i = p - 1;    for (int j = p; j < r; j++)    {        if (A[j] <= t)        {            i++;            if (i != j)            {                Exchange(A[i], A[j]);            }        }    }    Exchange(A[i + 1], A[r]);    return (i + 1);}void QuickSort(int A[], int p, int r){    if (p < r)    {        int t = Partition(A, p, r);        QuickSort(A, p, t - 1);        QuickSort(A, t + 1, r);    }}int _tmain(int argc, _TCHAR* argv[]){    int A[] = { 2, 4, 8, 5, 3, 1, 6 };    QuickSort(A,0,6);    for (int i = 0; i < 7; i++)    {        cout << A[i] << " ";    }    system("pause");    return 0;}
原创粉丝点击