首先,我看到了一个与C ++有关的类似问题,但我并不太了解它 - 而且我的问题是关于Java。
基本上我编写了两个方法,可以在解析的数组中使用SelectionSort和BubbleSort。虽然我相信我的方法正常工作(我已经运行了测试,他们都按升序对数字进行了排序),但我不是确定我是否正确计算比较次数和数字交换次数。如果有人能够在下面测试我的代码并提供一些反馈,我将非常感激。
注意:我可以压缩我的Java项目文件,并在需要时将其发送给任何人。
BubbleSort方法:
public String bubbleSort(int[] numbers)
{
System.out.println("******|Bubble Sort|******");
StringBuilder originalArray = new StringBuilder();
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
int temp; // temporary variable
//Set boolean variable to true,
//to allow the first pass.
boolean pass = true;
int comparisons = 0;
int swaps = 0;
//While a pass can be made,
while(pass)
{
//Set the boolean value to false,
//indicating a number swap could
//be made.
pass = false;
for(int i = 0; i < numbers.length - 1; i++)
{
//increment the number of comparisons by 1.
comparisons++;
if(numbers[i] > numbers[i+1])
{
temp = numbers[i];
numbers[i] = numbers[i + 1];
numbers[i+1] = temp;
//increment the amount of swaps made by 1,
//to put numbers in correct order.
swaps++;
pass = true;
}
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
SelectionSort方法
public String selectionSort(int[] numbers)
{
System.out.println("******|Selection Sort|******");
StringBuilder originalArray = new StringBuilder();
int comparisons = 0;
int swaps = 0;
for(int i = 0; i <= numbers.length - 1; i++)
{
originalArray.append(numbers[i] + " ");
}
System.out.println("Original array: " + originalArray);
//Declare variable to hold first element
int first;
//declare temporary variable, to be used in
//swapping integers.
int temp;
for(int x = numbers.length - 1; x > 0; x--)
{
first = 0;
comparisons++;
for(int y = 1; y <= x; y++)
{
//comparisons++;
if(numbers[y] > numbers[first])
{
first = y;
//comparisons++;
swaps++;
}
temp = numbers[first];
numbers[first] = numbers[x];
numbers[x] = temp;
//swaps++;
}
}
//Create a StringBuilder object - to hold
//the output of sorted numbers.
StringBuilder sb = new StringBuilder();
//Loop through the now sorted array - appending
//each subsequent number in the array to the
//StringBuilder object.
for(int i = 0; i < numbers.length; i++)
{
sb.append(numbers[i] + " ");
}
//Return the final results of the sorted array.
return "Sorted Array (asc): " + sb.toString() + "\nComparisons made: " + comparisons
+ "\nSwaps made: " + swaps;
}
答案 0 :(得分:4)
对于BUBBLE SORT:
主要比较 - &gt; (n *(n-1))/ 2
项目分配(互换) - &gt; 3 *(n-1)
选择排序:
主要比较 - &gt; (n *(n-1))/ 2 (与气泡相同)
项目分配(互换) - &gt; (n *(n-1))/ 4
(请注意 n 是您的数组大小的数量)