Java中:
原始数据类型的参数是 [color=red]传值[/color] 的
而
符合数据类型的参数是 [color=red]传引用[/color] 的
原始数据类型的参数是 [color=red]传值[/color] 的
而
符合数据类型的参数是 [color=red]传引用[/color] 的
class BubbleSort<T extends Comparable<T>> {
private T holder;
public void sort(T[] arr){
boolean soldier = true;
for (int i = arr.length - 1; i >= 0; i --){
soldier = true;
for (int j = i; j > 0; j --){
if (arr[j].compareTo(arr[j - 1]) < 0){
swap(arr, j, j - 1);
soldier = false;
}
}
if (soldier){
break;
}
}
}
//arr以引用的形式传入, idxOne和idxTwo以值的形式传入
public void swap(T[] arr, int idxOne, int idxTwo){
holder = arr[idxOne];
arr[idxOne] = arr[idxTwo];
arr[idxTwo] = holder;
}
public static void main(String[] args) {
BubbleSort<Integer> bs = new BubbleSort<Integer>();
Integer[] arr = {1, 7, 3, 8, 5};
bs.sort(arr);
for (int item : arr)
System.out.print(item + " ");
}
}
//Print Result: 1 3 5 7 8 (改变了原数组对象的值)