归并排序c++实现

void merge(int arr[], int left, int mid, int right)
{   
    std::vector<int> *result = new std::vector<int>();
    int l = left;
    int m = mid;
// std::cout <<"[";
// for(int i = left; i < mid; ++i)
// {
// std::cout << arr[i]<<"-";
// }
// for(int i = mid; i <= right; ++i)
// {
// std::cout << arr[i]<<"-";
// }
// std::cout <<"]"<<std::endl;
    while(l <= mid -1 && m <= right)
    {  
        if( arr[l] <= arr[m] ){
            result->push_back(arr[l++]);
        }           
        else {
            result->push_back(arr[m++]);
        }   
    }  
    while(l <= mid -1){
        result->push_back(arr[l++]);
    }  
    while(m <= right){
        result->push_back(arr[m++]);
    }
// std::cout << "sort[";
    for(auto item : *result)
    {
// std::cout << item<<"-"; 
        arr[left++] = item;
    }
// std::cout <<"]"<<std::endl;
}   
    
void mergeSort(int arr[], int left, int right)
{   
    if( right - left < 2) 
    {
        if( arr[left] > arr[right])
        {
            std::swap(arr[left], arr[right]);
        }
        return ;
    }
    int m = (right + left)/ 2 ;
    mergeSort(arr, left, m);
    mergeSort(arr, m+1, right);
    merge(arr, left, m+1, right);
}   
    
int main()
{   
    int test[10];
    for(int i = 0; i < 10; ++i)
    {
        test[i] = std::rand()%100;
    }
    std::cout <<"排序前"<< std::endl;
    for(int i = 0; i < 10; ++i)
    {
        std::cout << test[i]<<" " ;
    }
    std::cout << std::endl;
    mergeSort(test,0,9);
    std::cout <<"排序后"<< std::endl;                                                   
    for(int i = 0; i < 10; ++i)
    {
        std::cout << test[i]<<" " ;
    }
    std::cout << std::endl;
return 0;
} 

结果:
排序前
83 86 77 15 93 35 86 92 49 21
排序后
15 21 35 49 77 83 86 86 92 93

点赞