【数据结构-排序】交换排序

2019-09-29  本文已影响0人  jenye_
#include<iostream>
using namespace std;

int Partition(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(int A[],int low,int high){
    if(low<high){
        int pivotpos = Partition(A,low,high);
        QuickSort(A,low,pivotpos-1);
        QuickSort(A,pivotpos+1,high);
    }
}
int main(){
    int A[6] = {1,3,5,-1,2,10};
    cout<< "the len is " << sizeof(A)/sizeof(A[0]) << endl;
    int len = sizeof(A)/sizeof(A[0]);
    QuickSort(A,0,5);
    for(int i = 0; i < len; i++){
        cout<< A[i] <<" "; 
    } 
    cout<<endl;
}
上一篇 下一篇

猜你喜欢

热点阅读