我创建了一些使用冒泡排序对数组进行排序的代码,但有人告诉我,冒泡排序的变化表现更好,所以我想知道是否有更好的冒泡排序版本。例如,我正在使用常规版本,如下所示:
package termproject3;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class TermProject3 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
Scanner sc = new Scanner(System.in);
System.out.println("please enter the size of the array:");
int n = sc.nextInt();
System.out.println("Enter the number of iterations: ");
int num_i = sc.nextInt();
int swap;
int array[] = new int[n];
Random r = new Random();
long startTime = System.nanoTime();
for (int t = 0; t < num_i; t++){
System.out.println();
System.out.println( t+1 + ".- Array to be sorted: ");
for (int i = 0; i < n; i++) {
array[i] = r.nextInt(array.length);
System.out.print(array[i] + ", ");
}
System.out.println();
for (int i = 0; i < (n - 1); i++) {
for (int d = 0; d < n - i - 1; d++) {
if (array[d] > array[d + 1]) {
swap = array[d];
array[d] = array[d + 1];
array[d + 1] = swap;
}
}
}
System.out.println("Sorted list using bubble sort :");
for (int i = 0; i < n; i++) {
System.out.print(array[i] + ", ");
}
System.out.println();
}
long running_time = System.nanoTime() - startTime;
System.out.println("elapsed time: " +running_time+ " nano seconds");
System.out.println("which is " + running_time/1E9 + " seconds");
}
}
答案 0 :(得分:4)
我不知道你为什么要使用冒泡排序,但是Collections.sort(List)
和Collections.sort(List, Comparator)
实现了你可以使用的快速排序。
答案 1 :(得分:0)
这个答案可能对您有所帮助: Optimized Bubble Sort (Java)
值得注意的是,优化冒泡排序是一项愚蠢的练习,因为存在更快,更优雅的方法:
Collections.sort(List)