快速排序算法的递归和非递归实现

快速排序是对冒泡排序的改进,回想一下冒泡排序,他是每次在相邻的元素中交换使之有序,然后将数组分成了两个部分,前面的一部分无序,后面的一部分升序。

而快速排序是交换两个间距比较远的元素,一趟排序要经过交换的次数会小一些。

下面给出递归排序的代码

挖坑法

void sort(vector<int>&arr, int left, int right)
{
	if (left < right)
	{
		int m = partition(arr, left, right);
		sort(arr, left, m);
		sort(arr, m + 1, right);
	}
}
int partition(vector<int>&arr, int left, int right)
{
	int pivot = arr[left];
	while (left<right)
	{
		while (right > left && arr[right] >= pivot)
			right--;
		arr[left] = arr[right];

		while (left < right && arr[left] <= pivot)
			left++;
		arr[right] = arr[left];
		
	}
	arr[left] = pivot;
	return left;
}

非递归算法,就是用一个栈将未排序的两个部分保存起来,然后分别进行partition.

int partition(vector<int> &vec,int low,int high){
    int pivot=vec[low];  //任选元素作为轴,这里选首元素
    while(low<high){
        while(low<high && vec[high]>=pivot)
            high--;
        vec[low]=vec[high];
        while(low<high && vec[low]<=pivot)
            low++;
        vec[high]=vec[low];
    }
    //此时low==high
    vec[low]=pivot;
    return low;
}

void quicksort2(vector<int> &vec,int low,int high){
    stack<int> st;
    if(low<high){
        int mid=partition(vec,low,high);
        if(low<mid-1){
            st.push(low);
            st.push(mid-1);
        }
        if(mid+1<high){
            st.push(mid+1);
            st.push(high);
        }
        //其实就是用栈保存每一个待排序子串的首尾元素下标,下一次while循环时取出这个范围,对这段子序列进行partition操作
        while(!st.empty()){
            int q=st.top();
            st.pop();
            int p=st.top();
            st.pop();
            mid=partition(vec,p,q);
            if(p<mid-1){
                st.push(p);
                st.push(mid-1);
            }
            if(mid+1<q){
                st.push(mid+1);
                st.push(q);
            }       
        }
    }
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值