合并排序算法

时间:2011-04-11 08:41:50

标签: c++ mergesort

什么是C ++中“合并排序”的最佳算法,其中内存必须“最有效”使用?我只知道执行此操作的标准方法,但这不是如何使用内存的最有效方法。 这是我所知道的唯一变种:

#include <iostream>
using namespace std;
int main() {
int arr1[20]= {0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20};
int arr2[14]= {0,23,25,27,29,31,33,35,37,39,40,41,42,43};
int arr3[34];
int indexA=0, indexB=0, indexC=0;

while((indexA<20) && (indexB<14)) {
    if(arr1[indexA] < arr2[indexB]) {
        arr3[indexC] = arr1[indexA];
        indexA++;
    }
    else {
        arr3[indexC] = arr2[indexB];
        indexB++;
    }
    indexC++;
}

while(indexA<20) {
    arr3[indexC] = arr1[indexA];
    indexA++;
    indexC++;
}

while(indexB<14) {
    arr3[indexC] = arr2[indexB];
    indexB++;
    indexC++;
}

for (int i=0; i<34; i++)
    cout << arr3[i] << " ";
return 0;
}

任何人都可以告诉我一个更好的“Merge Sort”算法,它以“更有效”的方式使用内存吗?它也可以不是数组。

非常感谢你!

3 个答案:

答案 0 :(得分:2)

合并排序的常见问题是,对于每次递归,您最终都会使用全新的内存。结果需要O(N * log(n))存储器。事实证明,如果你更聪明一点,你可以用线性O(N)内存来做到这一点。只是不要制作新的数组,并根据需要在原始数组中交换元素。

答案 1 :(得分:0)

根据算法性质 - 合并排序需要一个额外的空间,您想要排序的数组大小相同。

您问题的答案。书中的“Java中的数据结构和算法 - 第二版由Robert Lafore”有一个例子,它只使用相同大小的重复数组,而不是创建多个子数组。你可以找到@

程序

http://homepage.cs.uiowa.edu/~sriram/21/fall07/code/mergeSort.java

以下示例仅以简单的方式解释mergesort。

import java.util.Arrays;
import java.util.Random;

public class SimpleMergeSort {

void mergeSort(int [] arr)
{
    if( arr.length <= 1)
        return;

    int mid = arr.length / 2;
    int [] left = Arrays.copyOfRange(arr, 0, mid);
    int [] right = Arrays.copyOfRange(arr, mid, arr.length);
    mergeSort(left);
    mergeSort(right);
    merge(left,right,arr);
}

void merge(int [] left, int [] right, int[] arr)
{
    int arrIndex = 0;
    int leftIndex = 0;
    int rightIndex = 0;

    //both left and right are not empty
    while( leftIndex < left.length && rightIndex < right.length)
    {
        if( left[leftIndex] < right[rightIndex])
        {
            arr[arrIndex++] = left[leftIndex++];
        }
        else
        {
            arr[arrIndex++] = right[rightIndex++];
        }
    }

    //if left still has some content
    while(leftIndex < left.length)
    {
        arr[arrIndex++] = left[leftIndex++];
    }

    //if right still has some content
    while(rightIndex < right.length)
    {
        arr[arrIndex++] = right[rightIndex++];
    }
}


public static void main(String[] args) {

    int [] array = new int[10];

    Random random = new Random();
    for(int i=0; i<array.length; i++)
    {
        array[i] = random.nextInt(1000);
    }
    System.out.println(Arrays.toString(array));
    SimpleMergeSort sort = new SimpleMergeSort();
    sort.mergeSort(array);
    System.out.println(Arrays.toString(array));

}

}

答案 2 :(得分:0)

而不是在主中使用合并和排序你可以使用递归,这会减少你在手动计算中的负荷并将数组分成两部分enter code here mid = beg + end / 2; a [求, .....,结束] //所以 a1 [求,...中] //和 A2 []中间+ 1,....端] then call the recursion functions check the base case carefully如果(大