java实现冒泡算法的几种方式

发表时间:2023-04-11 17:56:56点击:559

第一种,使用for循环

int[] arr = {10, 2, 43, 12, 26};
        int temp = 0;

        for(int i=0; i < arr.length; i++){
            for(int j=1; j < (arr.length-i); j++){
                if(arr[j-1] > arr[j]){
                    temp = arr[j-1];
                    arr[j-1] = arr[j];
                    arr[j] = temp;
                }
            }
        }

第二种,使用while循环

int[] arr = {10, 2, 43, 12, 26};
int temp = 0;
boolean swapped = true;

while(swapped){
    swapped = false;
    for(int i=0; i < arr.length-1; i++){
        if(arr[i] > arr[i+1]){
            temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
            swapped = true;
        }
    }
}

第三种,使用 do-while 循环

int[] arr = {10, 2, 43, 12, 26};
int temp = 0;
boolean swapped = true;

do{
    swapped = false;
    for(int i=0; i < arr.length-1; i++){
        if(arr[i] > arr[i+1]){
            temp = arr[i];
            arr[i] = arr[i+1];
            arr[i+1] = temp;
            swapped = true;
        }
    }
} while(swapped);

*原创文章,转载请注明出处