【快排】· 递归

思路:

快排的思路就是寻找一个分界点,左边的数均小于右边的。

那么如何来找这个分界点呢?

例如a[5] = {7,8,6,5,4}

7  8  6  5  4

l = 0 ; r = 4 a[l] > a[r] swap(a[l] ,a[r])  l++

4  8  6  5  7

l = 1;  r = 4 a[l] > a[r] swap(a[l] ,a[r])  l++

4  7  6  5  8

l = 2;  r = 4 a[l] < a[r] r--

4  7  6  5  8

l = 2;  r = 3 a[l] > a[r] swap(a[l] ,a[r])  l++

4  7  5  6  8

l = 3; r = 3

这样就将数组分成两部分a[0]-a[3] a[4]

这段代码有问题,但是暂时保留,过后改:

#include <iostream>
using namespace std;
void swap(int &a,int &b) {
	int temp;
	temp = a;
	a = b;
	b = temp;
}
 int Mid(int a[],int l,int r){
	if(l == r) return l;
	while(l < r){
		while(l < r && a[r] <= a[l]){
			swap(a[l],a[r]);
			l++;
		}
		while(l < r && a[r] > a[l]){
			r--;
		}
	}
	return l;
}
void QuickSort(int a[],int l,int r){
	if(l < r){
		int mid = Mid(a,l,r);
		QuickSort(a,l,mid);
		QuickSort(a,mid+1,r);
	}
	else if(l == r){
		return;
	}
}
int main() {
	
		int a[5] = {5,4,3,2,1};
		QuickSort(a,0,4);
		for(int i = 0; i < 5; i++)
			cout << a[i] << endl;
			
		/*int a = 0, b = 1;
		cout << a << ' ' << b << endl;
		swap(a, b);
		cout << a << ' ' << b << endl;*/
        system("pause");
        return 0;
}

课本代码:

#include <iostream>  
#include <vector>
using namespace std;  
int Mid(vector<int>& a,int low,int high){
	int pivot = a[low];
	while(low < high){
		while(low < high && a[high] >= pivot) 
			high--;
		a[low] = a[high];//这里一定是要先低后高,因为第一个数又被pivot存储起来,如果反过来的话,可能会出现某个值丢失
		while(low < high && a[low] <= pivot) 
			low++;
		a[high] = a[low];
	}
	a[low] = pivot;
	return low;
} 

void QuickSort(vector<int>& a,int l,int r){  
    if(l < r){  
        int mid = Mid(a,l,r);  
        QuickSort(a,l,mid);  
        QuickSort(a,mid+1,r);  
    }  
    else if(l == r){  
        return;  
    }  
}  
int main() {  
      
        int m[4] = {3,5,1,0};
		vector<int> a(m,m+4);
        QuickSort(a,0,3);  
        for(int i = 0; i < 4; i++)  
            cout << a[i] << endl;  
              
        /*int a = 0, b = 1; 
        cout << a << ' ' << b << endl; 
        swap(a, b); 
        cout << a << ' ' << b << endl;*/  
        system("pause");  
        return 0;  
}  


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值