【摘录】快速排序

 

摘录自《数据结构原理与经典问题求解》

 

#include "QuickSort.h"
#include <iostream>
using namespace std;
 
QuickSort::QuickSort(vector<int> _list, int _len)
{
    for (int i=0; i<_len; i++) list.push_back(_list[i]);
    this->len = _len;
}
 
//8 快速排序------------------------------------------------------------
void QuickSort::quick_sort(int left, int right)
{
    int i = left;
    int j = right;
    int pivot = list[left];
    
    while (i<j)
    {
        while (i<j && list[j]>=pivot) j--; //找到比基数小的元素
        if(i < j) swap(i, j);                           
        while (i<j && list[i]<=pivot) i++; //找到比基数大的元素
        if(i < j) swap(i, j);                         
    }
    
    if (i!=left) quick_sort(left, i-1);    //对list[left...i-1]排序
    if (j!=right) quick_sort(j+1, right);  //对list[j+1...right]排序
}
 
void QuickSort::swap(int i, int j)
{
    int temp = list[i];
    list[i] = list[j];
    list[j] = temp;
}
 
void QuickSort::out()
{
    for (int i=0; i<len; i++) 
    {
        cout<< list[i] << " ";
        if ((i+1)%18 == 0) cout<<endl;
    }
    cout <<endl;
}
 
 

 

 

QuickSort.h源代码如下

 

//快速排序
 
#ifndef QUICKSORT_H
#define QUICKSORT_H
 
#include <vector>
using namespace std;
 
class QuickSort
{
private:
    int len;
    vector<int> list;
public:
    QuickSort(vector<int> _list, int _len);
    void quick_sort(int,int);
    void swap(int,int);
    void out();
};
 
#endif
posted @ 2009-11-19 21:49  leukotrichia  阅读(217)  评论(0编辑  收藏  举报