2016-04-21 29 views
1

我必須做出以下2次修改一個簡單的冒泡排序程序:使2次修改到冒泡計劃

  1. 第一遍後,人數最多的是保證在最高編號的元素陣列;第二次過後,兩個最高的數字是「到位」;等等。不是每次都進行九次比較,而是修改冒泡排序以在第二遍中進行八次比較,在第三次中進行八次比較,依此類推。

  2. 數組中的數據可能已經按照正確的順序或接近正確的順序,那麼爲什麼如果少於9次就足夠了呢?修改排序以在每次通過結束時檢查是否有交換。如果沒有製作,數據必須已經按照正確的順序,所以程序應該終止。如果掉期已經做出,至少需要一個多通「。

任何幫助,以我應該如何處理這些將不勝感激!

//sort elements of array with bubble sort 
public static void bubbleSort (int array2[]) 
{ 

    //loop to control number of passes 
    for (int pass = 1; pass < array2.length; pass++) 
    { 

     //loop to control number of comparisons 
     for (int element = 0; element < array2.length - 1; element++) 
     { 

      //compare side-by-side elements and swap them if 
      //first element is greater than second element 
      if (array2[element] > array2[element + 1]){ 

       swap (array2, element, element + 1); 

      } 
     } 
    } 
} 
//swap two elements of an array 
public static void swap (int array3[], int first, int second) 
{ 
    //temporary holding area for swap 
    int hold; 
    hold = array3[first]; 
    array3[first] = array3[second]; 
    array3[second] = hold; 

} 

回答

0

我認爲這會爲你做。一個布爾被添加到檢查和運行(j)從input.length減去每次運行。

public static int[] bubbleSort(int input[]) 
{ 
    int i, j, tmp; 
    bool changed; 
    for (j = 0; j < input.length; j++) 
    { 
     changed = false; 
     for (i = 1; i < input.length - j; i++) 
     { 
      if (tmp[i-1] > input[i]) 
      { 
       tmp= input[i]; 
       input[i] = input[i-1]; 
       input[i-1] = tmp; 
       changed = true; 
      } 
     } 
     if (!changed) return input; 
    } 
    return input; 
}