zoukankan      html  css  js  c++  java
  • 归并排序方法


    #include <iostream>
    using namespace std;

    void mergearray(int a[], int first, int mid, int last, int temp[])
    {
    int i = first, j = mid + 1;
    int m = mid, n = last;
    int k = 0;

    while (i <= m && j <= n)
    {
    if (a[i] <= a[j])
    temp[k++] = a[i++];
    else
    temp[k++] = a[j++];
    }

    while (i <= m)
    temp[k++] = a[i++];

    while (j <= n)
    temp[k++] = a[j++];

    for (i = 0; i < k; i++)
    a[first + i] = temp[i];
    }
    void mergesort(int a[], int first, int last, int temp[])
    {
    if (first < last)
    {
    int mid = (first + last) / 2;
    mergesort(a, first, mid, temp); //左边有序
    mergesort(a, mid + 1, last, temp); //右边有序
    mergearray(a, first, mid, last, temp); //再将二个有序数列合并
    }
    }

    bool MergeSort(int a[], int n)
    {
    int *p = new int[n];
    if (p == NULL)
    return false;
    mergesort(a, 0, n - 1, p);
    delete[] p;
    return true;
    }


    int main()
    {
    int a[10] = { 3, 2, 1, 4, 5, 7, 6, 9, 8, 10 };
    MergeSort(a, 10);
    for (int i = 0; i < 10; i++)
    {
    cout << a[i] << " ";
    }
    }

  • 相关阅读:
    ORACLE表空间管理维护
    oracle表分区详解
    Jquery
    B
    A
    E
    字符串排成字典序,字符串数组
    命令,快捷键,配置
    第一个java程序
    A
  • 原文地址:https://www.cnblogs.com/wll-zju/p/4817538.html
Copyright © 2011-2022 走看看