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 (改变了原数组对象的值)
本文详细介绍了使用Java实现泛型冒泡排序算法的过程,并通过具体示例展示了如何对整数数组进行排序。文章解释了参数传递机制,即基本类型按值传递而复杂类型按引用传递的概念。此外,还提供了完整的代码示例及运行结果。
1032

被折叠的 条评论
为什么被折叠?



