不能用for/while,使用递归实现冒泡
和for/while一样,只是迭代的参数都要写成传参否则会丢失状态
下面的代码loop表示每次的冒泡遍历次数,执行时依次递减。
1. 递归冒泡代码:
/*
* a recursive way of bubbleSort
*@param arr
*the input array of int
*@param i
*the current index of arr
*@param loop
*maximum loops needed for each traverse,started at arr.length-1
*,ended at 1
*@param swap
*an indicator which shall be false when starting the sort
*, showing if a swap happens
*/
public static void bubbleSort(int[] arr, int i, int loop, boolean swap){
if(loop>=1){
if(i<loop){
if (arr[i]>arr[i+1]){
int tmp =arr[i+1];
arr[i+1]= arr[i];
arr[i] = tmp;
swap = true;
}
//inner loop
bubbleSort(arr,++i,loop,swap