10个元素的一维数组如果使用冒泡排序进行,需要几次冒泡循环才能完成排序 为什么 谢谢!

解决方案 »

  1.   

    看if那段,自己想逻辑。public static void main(String[] args) {
    int[] tempNums = { 1, 2, 3, 4, 5, 6, 7, 10, 9, 11 };
    int count = 0;
    for (int i = 0; i < tempNums.length; i++) {
    for (int j = 0; j < tempNums.length - i - 1; ++j) {
    if (tempNums[j] > tempNums[j + 1]) {
    count++;
    int temp = tempNums[j];
    tempNums[j] = tempNums[j + 1];
    tempNums[j + 1] = temp;
    } }
    }
    System.out.println("排序了"+count+"次!");
    }
      

  2.   


    外层循环10次,内层n-i次所以是10+9+8+7+6+5.....+1 = 55次循环楼上的注意,lz问的是循环次数,不是比较次数!
      

  3.   

    循环次数
    public static void main(String[] args) {
    int[] tempNums = { 1, 2, 3, 4, 5, 123, 99, 100, 9, 11 };
    int count = 0;
    for (int i = 0; i < tempNums.length; i++) {
    System.out.println("i为"+i+"时");
    System.out.print("j为");
    for (int j = 0; j < tempNums.length - i - 1; ++j) {
    System.out.print(j+",");
    count++;
    if (tempNums[j] > tempNums[j + 1]) {
    int temp = tempNums[j];
    tempNums[j] = tempNums[j + 1];
    tempNums[j + 1] = temp;
    } }
    System.out.println("\n-------------------");
    }
    System.out.println("循环了"+count+"次!");
    }