2013-05-07 68 views
2

我正在努力学习一个测试和其中一个研究问题,我无法与BubbleSort达成交易。问题是:修改BubbleSort代码

修改下面的BubbleSort代码来短路它的执行。我的意思是,修改它,以便如果通过完成而不进行任何交换,执行将停止。

public static<T extends Comparable<T>> void bubbleSort(T[] data) 
{ 
    int position, scan; 
    T temp; 

    for (position = data.length - 1; position >= 0; position--) 
    { 
    for (scan = 0; scan <= position - 1; scan++) 
    { 
     if (data[scan].compareTo(data[scan+1]) > 0) 
     { 
     /**Swap the values*/ 
     temp = data[scan]; 
     data[scan] = data[scan+1]; 
     data[scan + 1] = temp; 
     } 
    } 
    } 
}  

回答

2

您将需要一个布尔标志或状态。

快速谷歌搜索会救你的麻烦:http://rosettacode.org/wiki/Sorting_algorithms/Bubble_sort

repeat 
    hasChanged := false 
    decrement itemCount 
    repeat with index from 1 to itemCount 
     if (item at index) > (item at (index + 1)) 
      swap (item at index) with (item at (index + 1)) 
      hasChanged := true 
until hasChanged = false 
+0

我想我错过了联系,但谢谢!对此,我真的非常感激 – Megan 2013-05-07 00:23:06