排序算法 C++实现

一、插入排序 (Insertion Sort)

void insertion_sort(vector<int>& number){
    int length = number.size();
    if(length <= 1) return;
    
    for(int index = 1; index < length; ++index){
        int temp = number[index];
        int compare = index;
        for(; compare > 0 && temp < number[compare-1]; compare--)
            number[compare] = number[compare-1];
        number[compare] = temp;
    }
}

 

二、 快速排序(Quick Sort)

void quick_sort(vector<int>& number, int begin, int end){

    if(begin >= end) return;
    int mid = (begin+end)/2, pivot = number[mid];
    swap(number[mid], number[end]);
    
    int temp = begin - 1;
    for(int i = begin; i < end; i++)
        if(number[i] <= pivot)
            swap(number[++temp], number[i]);
    swap(number[++temp], number[end]);
    
    quick_sort(number, begin, temp-1);
    quick_sort(number, temp+1, end);
}

 

 三、归并排序(Merge Sort)

void MergeSort(vector<int>& number){
    vector<int> temp(number.size());
    mergesort(number, temp, 0, number.size()-1);
    //number.swap(temp);
}

void mergesort(vector<int>& number, vector<int>& temp, int begin, int end){
    if(begin < end){
        int center = (begin + end)/2;
        mergesort(number, temp, begin, center);
        mergesort(number, temp, center+1, end);
        merge(number, temp, begin, center+1, end);
    }
}
    
void merge(vector<int>& number, vector<int>& temp, int left, int right, int end){
    int leftend = right - 1;
    int tmpIndex = left;
    int total = end - left + 1;
    while(left <= leftend && right <= end){
        if(number[left] < number[right])
            temp[tmpIndex++] = number[left++];
        else
            temp[tmpIndex++] = number[right++];
    }
    
    while(left <= leftend)
        temp[tmpIndex++] = number[left++];
    
    while(right <= end)
        temp[tmpIndex++] = number[right++];
        
    for(int i = 0; i < total; ++i, --end)
        number[end] = temp[end];
}

 

 

示例代码:

#include <iostream>
#include <vector>

using namespace std;

void MergeSort(vector<int>&);
void mergesort(vector<int>&, vector<int>&, int, int);
void merge(vector<int>&, vector<int>&, int, int, int);

int main()
{
    vector<int> numbers = {34,8,64,51,21,1,23,45,90,540,47,35,70,134,152,251};
    // 1 8 21 23 34 35 45 47 51 64 70 90 134 152 251 540
    
    // insertion_sort(numbers);
    // quick_sort(numbers, 0, numbers.size()-1);
    MergeSort(numbers);
    for(int num : numbers)
        cout << num << ' ' ;
    return 0;
}

 

转载于:https://www.cnblogs.com/heifengli/p/11329465.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值