快速排序C++版

 //
//  main.cpp
//  QuickSort
//
//  Created by 陈亚东 on 15/3/10.
//  Copyright (c) 2015年 陈亚东. All rights reserved.
//

#include <iostream>

using namespace std;

void Swap(int& a, int& b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

int Partition(int a[], int low, int high)
{
    // 切分点pivot必须为第一个或最后一个,不能为中间的
    int pivot = a[low];
    
    int i = low, j = high; // i!=low+1;因为无法排序4,3,2,1这种, 如i < 跳出
    while (i < j) {
        // 必须先减才行,否则i可能不是low了,找到右边第一个最小的 1,4,3,2找到1
        while ( (i < j) && a[j] >= pivot ) {
            --j;
        };
        
        while ( (i < j) && a[i] <= pivot ) { // 找到左边第一个最大的
            ++i;
        };
        
        if (i >= j) // 只是为了防止再次交换
            break;
        
        Swap(a[i], a[j]);
    }
    
    Swap(a[low], a[i]);
    
    return i; // j是小于pivot的最大index
}

void QuickSort(int a[], int low, int high)
{
    if (low < high) {
        int partition = Partition(a, low, high);
        cout <<partition << endl;
        QuickSort(a, low, partition-1);
        QuickSort(a, partition+1, high);
    }
}


int main(int argc, const char * argv[])
{
  //int a[] = {4,1,2,6,9,5,3,4,6};
  //  int a[] = {5,4,3,2,1};
    int a[] = {1,2,3,4,5};
    int len = sizeof(a) / sizeof(int);
    
    QuickSort(a,0,len-1);

    for (int i = 0; i < len; ++i)
        cout << a[i] << ",";
    cout << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值