[英]Swap method taking an array and two integer indexes of the array as parameters
以下代碼用於快速排序類。 在底部,有一個稱為swap的方法,該方法應該獲取一個數組並交換數組中的兩個數字。 這在Java中可行嗎? 換句話說,是否有一種格式為swap(T [],int,int)的方法可以在這種情況下使用? 我希望我的問題有道理。
public class QuickSort {
public static <T extends Comparable<T>> void sort(T[] table) {
quickSort(table, 0, table.length - 1);
}
private static <T extends Comparable<T>> void quickSort(T[] table, int first, int last) {
if (first < last) {
int pivIndex = partition(table, first, last);
quickSort(table, first, pivIndex - 1);
quickSort(table, pivIndex + 1, last);
}
}
private static <T extends Comparable<T>> int partition(T[] table, int first, int last) {
T pivot = table[first];
int up = first;
int down = last;
do {
while ((up < last) && (pivot.compareTo(table[up]) >= 0)) {
up++;
}
while (pivot.compareTo(table[down]) < 0) {
down--;
}
if (up < down) {
swap(table, up, down);
}
}
while (up < down);
swap(table, first, down);
return down;
}
是的,您可以這樣做,因為在Java中,數組是一個對象,所以當您傳遞它時,實際上就是在內存中傳遞它的地址。 然后,被調用的函數可以對其進行操作,並且這些更改將在所有地方反映出來。
您可能正在考慮可以在C ++中完成的某些事情,而在Java中無法做到的,這就是swap(int x, int y)
。 因為Java中的原始數據值沒有地址(無論如何,程序員都沒有可用的地址),所以無法傳遞其地址,因此可以在非本地修改它們。
那有意義嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.