【发布时间】:2021-12-11 00:59:22
【问题描述】:
我在下面有冒泡排序的代码。我想知道如何才能更高效地运行并减少循环次数
package bubbleSort;
public class BubbleSort {
public static void main(String[] args) {
// initialize array to sort
int size = 10;
int[] numbers = new int[size];
// fill array with random numbers
randomArray(numbers);
// output original array
System.out.println("The unsorted array: ");
printArray(numbers);
// call the bubble sort method
bubbleSort(numbers);
// output sorted array
System.out.println("The sorted array: ");
printArray(numbers);
}
public static void bubbleSort(int tempArray[]) {
//bubble sort code goes here (you code it)
// loop to control number of passes
for (int pass = 1; pass < tempArray.length; pass++) {
System.out.println(pass);
// loop to control number of comparisions for length of array - 1
for (int element = 0; element < tempArray.length - 1; element++) {
// compare side-by-side elements and swap tehm if
// first element is greater than second elemetn swap them
if (tempArray [element] > tempArray [element + 1]) {
swap (tempArray, element, element + 1);
}
}
}
}
public static void swap(int[] tempArray2,int first, int second) {
//swap code goes here (you code it)
int hold; // temporary holding area for swap
hold = tempArray2 [first];
tempArray2 [first] = tempArray2 [second];
tempArray2 [second] = hold;
}
public static void randomArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
tempArray[i] = (int) (Math.random() * 100) + 1;
}
}
public static void printArray(int tempArray[]) {
int count = tempArray.length;
for (int i = 0; i < count; i++) {
System.out.print(tempArray[i] + " ");
}
System.out.println("");
}
}
任何帮助将不胜感激。我是编码新手,对于如何提高效率并减少循环次数感到非常困惑。
【问题讨论】:
-
冒泡排序不是一种高效的排序方法。无论您在哪里了解冒泡排序,肯定都会有一段/章节介绍其他更有效的排序方法,例如快速排序。
-
O(n^2) 的意思是,通过某种优化使冒泡排序更有效确实没有意义,因为它要么是 a.) 不再是冒泡排序,要么是 b .) 仍然具有相同的复杂性,并且当要排序的项目数量增加时变得非常慢。冒泡排序的最佳改进是选择different sorting algorithm。在这一点上,冒泡排序基本上只是作为一种易于学习的排序算法而存在。
-
您可以通过减少内部循环的跨度来改进冒泡排序的实现。在最大(最小)元素已经完全冒泡之后 - 无需将其包括在任何进一步的比较中。在en.wikipedia.org/wiki/Bubble_sort 查找“优化冒泡排序”部分
标签: java sorting bubble-sort