2014-03-19 90 views
0

我正在为我的CS类进行非递归合并排序,它不完全正常工作。我知道它被调用,因为当我运行测试程序时,它会改变数组,只是没有按照正确的顺序。有人可以帮忙吗?谢谢!非递归合并排序Java

private static void mergeSort(int[] a, int left, int right) 
{ 
    int midPoint = ((right + left)/2); 
    int[] buffer = new int[19]; 

    selectionSort(a, left, midPoint); 
    selectionSort(a, midPoint-1, right); 
    merge(a, buffer, 0, 9, 19); 
} 

private static void selectionSort(int[] a, int beginning, int end) 
{ 
    int [] temp = new int[end-1]; 

    for(int y = 0; y < end - 1; y++) 
    { 
     temp[y] = a[y]; 
    } 

    for (int i = 0; i < temp.length - 1; i++) 
    { 
     int minIndex = findMinimum(temp, i); 
     if (minIndex != i) 
      swap (temp, i, minIndex); 
    } 
} 

private static int findMinimum(int[] a, int first) 
{ 
    int minIndex = first; 

    for (int i = first + 1; i < a.length; i++) 
    { 
     if (a[i] < a[minIndex]) 
      minIndex = i; 
    } 
    return minIndex; 
} 

private static void swap(int []a, int x, int y) 
{ 
    int temp = a[x]; 
    a[x] = a[y]; 
    a[y] = temp; 
} 

private static void merge(int[] a, int[] temp, int left, int mid, int right) { 
    if (mid >= a.length) return; 
    if (right > a.length) right = a.length; 
    int i = left, j = mid+1; 
    for (int k = left; k < right; k++) { 
     if  (i == mid)  
      temp[k] = a[j++]; 
     else if (j == right)  
      temp[k] = a[i++]; 
     else if (a[j] < a[i]) 
      temp[k] = a[j++]; 
     else     
      temp[k] = a[i++]; 
    } 
    for (int k = left; k < right; k++) 
     a[k] = temp[k]; 
} 
+0

为什么在调用'selectionSort'时使用参数'left'和'right',中点'midPoint' - 调用'merge'时使用硬连线常量?为什么你硬连线'buffer'的长度 - 为什么不'int [] buffer = new int [a.length]'? – ajb

+0

我手动连接它们以确保参数具有正确的值,并且忘记将它们作为参数 – user3266115

回答

1

可能有其他错误,而是一个伸出的是selectionSort实际上并没有做任何的阵列。你传递一个数组引用作为a参数:

private static void selectionSort(int[] a, int beginning, int end) 

由于这是一个参考,如果selectionSort做过任何分配给的a任何元素,比如

a[x] = y; 

它会改变的元素调用者的数组,就像你想要的一样。但selectionSort中没有任何声明会改变a中的任何内容。该代码将元素复制到temp,与temp一起使用 - 但是然后将所有工作都抛弃。

+0

谢谢!我意识到selectonSort中的整个临时事物是不必要的。我刚刚摆脱它,并在第二个循环开始它,并将所有的温度改为一个,它的工作!谢谢一堆! – user3266115