我是相當新到Java。我正在int數組上創建排序算法,以便每個方法都保持它們所做交換和比較次數的計數。我遇到了顯示原始訂單,分揀訂單,交換和比較的麻煩。不知道我需要做些什麼來解決它。任何幫助將不勝感激。Java的泡沫分揀需要數互換和比較
public class IntBubbleSorter {
public static void bubbleSort(int[] array)
{
int lastPos;
int index;
int temp;
int count = 0;
int count2 = 0;
for (lastPos = array.length - 1; lastPos >= 0; lastPos--)
{
for (index = 0; index <= lastPos - 1; index++)
{
count2++;
if (array[index] > array[index + 1])
{
count++;
temp = array[index];
array[index] = array[index + 1];
array[index + 1] = temp;
}
}
}
System.out.print("\n Swaps:" + count);
System.out.print("\n Comparisons:" + count2);
}
}
public class SortingTest {
public static void main(String[] args)
{
int[] values = { 1,53,86,21,49,32,90,65,33,11,34,68,54,32,78,80,35,22,96,59,265,44324,123,3123,25435};
System.out.println("Original Order: ");
for (int element : values)
System.out.print(element + " ");
IntBubbleSorter.bubbleSort(values);
System.out.println("\nSorted order: ");
for (int element : values)
System.out.print(element + " ");
System.out.println();
}
}
//這是它是根據你的意見,你可以讓你的計數變量靜態的,把你輸出的主要方法,像這樣輸出
Original Order:
1 53 86 21 49 32 90 65 33 11 34 68 54 32 78 80 35 22 96 59 265 44324 123 3123 25435
Swaps:80
Comparisons:300
Sorted order:
1 11 21 22 32 32 33 34 35 49 53 54 59 65 68 78 80 86 90 96 123 265 3123 25435 44324
爲什麼你認爲這是不正確的? –
主要方法是讓原來的訂單,但隨後將泡沫分揀和獲得互換和比較,然後回到主方法得到的排序,這不是我想要的,但任何事情我儘量不工作的順序。我將創建更多使用相同主要方法的排序方法,我認爲它會變得非常混亂和混亂。我應該有某種「獲取」方法來獲得交換和比較? – Nosuchluck
這似乎夠合理。您可能會考慮創建某種抽象基類來實現比較和交換功能,然後您的各種排序實現可以繼承通用功能。我相信[塞奇威克(http://www.informit.com/store/algorithms-in-java-parts-1-4-9780201361209)採取了這種做法。 –