zoukankan      html  css  js  c++  java
  • 递归实现归并排序

    代码挺简单的,如下:

    /*
        实现归并排序算法
    */
    
    #include<iostream>
    
    using namespace std;
    int scope;
    
    void merge(int arr[], int left, int mid, int right)
    {
        int num_1=mid-left+1;
        int num_2 = right - mid;
        int temp_1[10001];
        int temp_2[10001];
        int i = 0;
        int j = 0;
        for (; i < num_1; i++)
        {
            temp_1[i] = arr[left + i];
        }
        for (; j < num_2; j++)
        {
            temp_2[j] = arr[mid + 1+j];
        }
    
        int k = left;
        i = 0;
        j = 0;
        while (i < num_1&&j < num_2)
        {
            if (temp_1[i] <= temp_2[j])
                arr[k++] = temp_1[i++];
            else
                arr[k++] = temp_2[j++];
        }
        
        while (i < num_1)
        {
            arr[k++] = temp_1[i++];
        }
        while (j < num_2)
        {
            arr[k++] = temp_2[j++];
        }
        
    
    }
    
    void mergeSort(int arr[], int left, int right)
    {
        int mid;
        if (left < right)
        {
            mid = (left + right) / 2;
            mergeSort(arr, left, mid);
            mergeSort(arr, mid + 1, right);
            merge(arr, left, mid, right);
        }
    
    }
    
    int main()
    {
        
        int arr[10001];
        cout << "enter the scope of the array:";
        cin >> scope;
    
        cout << "enter " << scope << " element of the array:" << endl;
        for (int i = 0; i < scope; i++)
        {
            cin >> arr[i];
        }
        mergeSort(arr, 0, scope-1);
        for (int i = 0; i < scope; i++)
            cout << arr[i] << " ";
    }
  • 相关阅读:
    spoj705
    bzoj2440
    spoj220
    bzoj2301
    hdu1695
    poj3294
    hdu3518
    poj3693
    函数
    样式
  • 原文地址:https://www.cnblogs.com/romantic-Right/p/4892767.html
Copyright © 2011-2022 走看看