快速排序【遞迴】【非遞迴】

Laox1ao發表於2018-06-04

單純記錄一下
Partition函式

int Partition(vector<int>& nums, int start, int end){
    if(start==end){
        return start;
    }
    int index = end;
    int small = start-1;
    for(int i=start;i<end;i++){
        if(nums[i]<nums[index]){
            small++;
            if(i!=small){
                swap(nums[i],nums[small]);
            }
        }
    }
    swap(nums[small+1],nums[end]);
    return small+1;
}

遞迴QuickSort

void QuickSort_Recur(vector<int>& nums, int start, int end){
    if(start>=end){
        return;
    }
    int index = Partition(nums,start,end);
    QuickSort_Recur(nums,start,index-1);
    QuickSort_Recur(nums,index+1,end);
}

非遞迴QuickSort

void QuickSort_Loop(vector<int>& nums){
    stack<int> indexs;
    int start=0, end=nums.size()-1;
    int index = Partition(nums,start,end);
    if(start<index-1){
        indexs.push(start);
        indexs.push(index-1);
    }
    if(index+1<end){
        indexs.push(index+1);
        indexs.push(end);
    }
    while(!indexs.empty()){
        int high = indexs.top();
        indexs.pop();
        int low = indexs.top();
        indexs.pop();
        int index = Partition(nums,low,high);
        if(low<index-1){
            indexs.push(low);
            indexs.push(index-1);
        }
        if(index+1<high){
            indexs.push(index+1);
            indexs.push(high);
        }
    }
}

相關文章