码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序算法的基本实现

时间:2014-11-11 10:36:22      阅读:169      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   ar   sp   for   div   log   bs   

/* ******* QSort.cpp **********
********* 快速排序实现 ********** */

#include "stdafx.h"
#include <list>
using namespace std;

template <typename T>
void Sort(T* a, int n)
{
    if (n <= 1)
    {
        return;
    }

    if (n == 2)
    {
        T& left = a[0];
        T& right = a[1];

        if (left > right)
        {
            swap(left, right);
        }
        return;
    }

    swap(*a, a[n>>1]);
    T* L = a + 1;
    T* R = a + n - 1;
    T v = a[0];
    while(L < R)
    {
        while(L < R && *L < v)L++;
        while(R > a && *R >= v)R--;
        if (L < R)
        {
            swap(*L, *R);
        }
    }
    swap(*a, *R);

    Sort(a, R - a);
    Sort(R + 1, n - 1 - (R - a));
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a[10];
    for (int i = 0; i < 10; i++)
    {
        a[i] = 10 - i;
    }

    Sort<int>(a, 10);

    return 0;
}

 

快速排序算法的基本实现

标签:style   blog   color   ar   sp   for   div   log   bs   

原文地址:http://www.cnblogs.com/autumoonchina/p/4088688.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!