c++实现几种常见排序算法

一、快速排序


int getPivot(vector<int>& arr, int left, int right){
    int tmp = arr[left];
    while(left < right){
        while(left < right && arr[right] >= tmp){
            right --;
        }
        arr[left] = arr[right];
        while(left < right && arr[left] <= tmp){
            left ++;
        }
        arr[right] = arr[left];
    }
    arr[left]  = tmp;
    return left;
}

void quickSort(vector<int>& arr, int left, int right){
    if(left < right){
        int pivot = getPivot(arr, left, right);
        quickSort(arr,left, pivot - 1);
        quickSort(arr, pivot + 1, right);
    }
}

二、冒泡排序

void bubbleSort(vector<int>& arr){
    int size = arr.size();
    for(int i = 1; i < size; i++){
        for(int j = 0; j < size - i; j++){
            if(arr[j] > arr[j + 1]){
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

三、堆排序

void adjustHeap(vector<int>& arr, int start, int end){
    int parent = start;
    int child = start*2 + 1;
    while(child <= end){
        if(child + 1 <= end && arr[child] < arr[child + 1] ){
            child++;
        }
        if(arr[parent] > arr[child]){
            return;
        }
        swap(arr[parent], arr[child]);
        parent = child;
        child = child * 2 + 1;
    }
}
void heapSort(vector<int>& arr){
    int size = arr.size();
    for(int i = size/2 - 1; i >= 0; i--){
        adjustHeap(arr, i, size - 1);
    }
    for(int i = size - 1; i >= 0; i--){
        swap(arr[0], arr[i]);
        adjustHeap(arr, 0, i - 1);
    }
}

四、归并排序

void merge(vector<int>& arr, int left, int mid, int right){
    vector<int> tmp;
    int i = left, j = mid + 1;
    while(i <= mid && j <= right){
        if(arr[i] < arr[j]){
            tmp.emplace_back(arr[i++]);
        }else{
            tmp.emplace_back(arr[j++]);
        }
    }
    while(i <= mid){
        tmp.emplace_back(arr[i++]);
    }
    while(j <= right){
        tmp.emplace_back(arr[j++]);
    }
    int m = left;
    int n = 0;
    while(m <= right){
        arr[m++] = tmp[n++];
    }
}

void mergeSort(vector<int>& arr, int left, int right){
    if(left >= right) return;
    int mid = left + ((right - left) >> 1);
    mergeSort(arr, left, mid);
    mergeSort(arr, mid + 1, right);
    merge(arr, left, mid, right);
}

posted on 2022-01-26 23:53  七昂的技术之旅  阅读(36)  评论(0编辑  收藏  举报

导航