2016-08-28 33 views
-3

以下程序是我在互联网上发现的快速排序算法的实现。对本地数组所做的更改如何反映到全局数组中?

public class QuickSort { 

    private int array[]; 
    private int length; 

    public void sortElements(int[] arrayvalues) { 

     if (arrayvalues == null || arrayvalues.length == 0) { 
      return; 
     } 
     this.array = arrayvalues; 
     length = arrayvalues.length; 
     doQuickSort(0, length - 1); 
    } 

    private void doQuickSort(int lowIndex, int highIndex) { 

     int i = lowIndex; 
     int j = highIndex; 

     int pivot = array[lowIndex + (highIndex - lowIndex)/2]; 

     // now Divide the array into two arrays(actually we are maintaining single array only) 
     while (i <= j) { 

      while (array[i] < pivot) { 
       i++; 

      } 
      while (array[j] > pivot) { 
       j--; 
      } 
      if (i <= j) { 
       swapElements(i, j); 

       //move index to next position on both sides 
       i++; 
       j--; 

      } 
     } 

     // call quickSort() method recursively 
     if (lowIndex < j) { 

      doQuickSort(lowIndex, j); 
     } 
     if (i < highIndex) { 

      doQuickSort(i, highIndex); 

     } 
    } 

    private void swapElements(int i, int j) { 

     int temp = array[i]; 
     array[i] = array[j]; 
     array[j] = temp; 

    } 

    public static void main(String a[]) { 

     QuickSort quicksort = new QuickSort(); 
     int[] inputarray = {32, 1, 23, 14, 43, 7, 6, 65}; 

     System.out.println("Before sorting"); 
     for (int i : inputarray) { 
      System.out.print(i); 
      System.out.print(" "); 
     } 

     quicksort.sortElements(inputarray); 

     System.out.println("After sorting"); 
     for (int i : inputarray) {  //Problem line 
      System.out.print(i); 
      System.out.print(" "); 
     } 
    } 
} 

一切都很好,直到最后一块,排序后打印数组。 for循环再次在inputarray上运行。 inputarray是在main中定义的,然后传递给sortElements,将它分配给在程序开始时定义的全局数组。所有后续的操作都在该全局数组上执行。那么应该在最后的for循环中打印?全局数组上的操作如何在输入数组中反映出来?

+0

指定一个像this.array = arrayvalues这样的变量的引用不会创建值的副本 - 它只是让这两个变量指向同一个数组。如果这是您的意图,您需要实际复制数组(例如'Arrays.copyOf(arrayvalues,arrayvalues.length)')。 –

+0

请注意,无论如何将变量'array'和'length'分配给变量是一个限制性的想法 - 这使得'QuickSort'类不可重入(基本上,你不能在'QuickSort的同一个实例上调用'sortElements' '从两个线程)。您可以将'array'作为参数传递给需要它的方法。 –

+0

[是Java的“传递引用”还是“传递值”?]的可能重复(http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass按值) – Raedwald

回答

0

当你写

this.array = arrayvalues; 

你实际上并没有复制arrayvalues:你只是做this.array指向同一个阵列arrayvalues点(他们都只是参考)。

因此,当您更改this.array的元素时,您也正在更改由arrayvalues指向的数组元素,因为它是同一个对象。

如果你真的打算带走的arrayvalues副本,这样做的:是这样的:

this.array = Arrays.copyOf(arrayvalues, arrayvalues.length); 

现在,他们指向不同的数组,因此更新一个未在其他的体现。

然而,这是不是真的清楚为什么你想要的是:如果你拿一个副本,在QuickSort类完成更新反映输入数组中:基本上,你不能再看看sortElements方法发生了什么变化。

因此,我会质疑为什么你不希望代码以目前的方式工作。

+0

我的印象是this.array = arrayvalues;通过创建两个不同的数组来复制数组中的arrayvalues的内容。但是现在你已经提到上述语句不会复制内容,而只是使数组引用数组值,所有内容都是合理的。感谢您的帮助哥们。 :) – Aamirmapkar

相关问题