以下程序是我在互联网上发现的快速排序算法的实现。对本地数组所做的更改如何反映到全局数组中?
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循环中打印?全局数组上的操作如何在输入数组中反映出来?
指定一个像this.array = arrayvalues这样的变量的引用不会创建值的副本 - 它只是让这两个变量指向同一个数组。如果这是您的意图,您需要实际复制数组(例如'Arrays.copyOf(arrayvalues,arrayvalues.length)')。 –
请注意,无论如何将变量'array'和'length'分配给变量是一个限制性的想法 - 这使得'QuickSort'类不可重入(基本上,你不能在'QuickSort的同一个实例上调用'sortElements' '从两个线程)。您可以将'array'作为参数传递给需要它的方法。 –
[是Java的“传递引用”还是“传递值”?]的可能重复(http://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass按值) – Raedwald