快速排序法之一

	//mian
        vector<int> temp;
	vector<int> id;
	for(int r=0; r<10;r++){
		int t = rand()%100+1;//0~100
		temp.push_back(t);
		cout<<t<<"  ";
	}
	cout<<endl;


	sortvect::quick_sort(temp,id);

	for(int r=0; r<10;r++){

		cout<<temp[r]<<"  ";
	}
	cout<<endl;

	for(int r=0; r<10;r++){

		cout<<id[r]<<"  ";
	}
	cout<<endl;

/*
 * sortvect.h
 *
 *  Created on: 2013-5-12
 *      Author: yutian
 */

#ifndef SORTVECT_H_
#define SORTVECT_H_

#include "iostream"
#include <fstream>
#include <algorithm>
#include<io.h>
#include<vector>
#include<time.h>
using namespace std;
class sortvect{
public:
	template <class T>
	//从小到大排序,id存放排序后的索引
	static vector<T> quick_sort(vector<T>& A, vector<int>& id);
	template <class T>
	static int partition(vector<T>& A,vector<int>& id, int left,int right);
	template <class T>
	static void QUICKSORT(vector<T>& A, vector<int>& id, int b, int e);

	template <class T>
		static void printv(vector<T> A);

};
/**
 * 从小到大
 * 分解:数组A[n]被划分两个字数组A[0..q-1]和A[q+1..n],使得对于数组A[0..q-1]中的元素都小于等于A[q], A[q+1..n]中的元素都大于等于A[q]。此时A[q]就得排好序。

解决:通过递归调用快速排序,对字数组A[0..q-1]和A[q+1..n]进行排序

合并:因为两个字数组已经是就地排好序的了,整个数组已经排好序了。
 */
template<class T>
inline vector<T> sortvect::quick_sort(vector<T>& A, vector<int>& id) {
	if(id.size()==0){
		for(int r=0; r<A.size(); r++){
			id.push_back(r);
		}
	}

	int s_left = 0;
	int s_right = A.size()-1;
	QUICKSORT(A, id, s_left, s_right);

	return A;
}

template<class T>
inline int sortvect::partition(vector<T>& A, vector<int>& id, int b, int e) {
	 int i, j, aim,  tmpid;
	 T tmp;
	    i = b - 1;
	    j = b;
	    aim = e;//尾数作为比较对象
	    while( j <= e-1)
	    {
	    	//i和j之间(不包括i,j执行比较判定)的数都比A[aim]大
	        if(A[j] <= A[aim])
	        {
	            i ++;
	            tmp = A[i];
	            A[i] = A[j];
	            A[j] = tmp;

	            tmpid = id[i];
	            id[i] = id[j];
	            id[j] = tmpid;
	        }
	        j ++;
	    }
	    T t = A[aim];
	    A[e] = A[i+1];
	    A[i+1] = t;

	    int tid = id[aim];
	    id[e] = id[i+1];
	    id[i+1] = tid;

	    printv(A);
	    printv(id);
	    return i + 1;
}

template<class T>
inline void sortvect::QUICKSORT(vector<T>& A, vector<int>& id, int b, int e) {
    int q;
    if(b < e)                    //当b==e时,只有一个元素,无需排序
    {
        q = partition(A, id, b, e);  //查找划分元素的位置
        QUICKSORT(A, id, b, q-1);
        QUICKSORT(A, id, q+1, e);
    }
}

template<class T>
inline void sortvect::printv(vector<T> A) {

	for(int r=0; r<A.size();r++){

		cout<<A[r]<<"  ";
	}
	cout<<endl;
}

#endif /* SORTVECT_H_ */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值