# 为什么使用冒泡排序时,数据逆序反而比随机的要快

0

【数组都是插满数据的】

PS：数据排序是按升序排序的，逆序时为降序的....

真心请各位赐教....本人不胜感激....

KeenLeung | 初学一级 | 园豆：177

0

0

angelshelter | 园豆：9887 (大侠五级) | 2012-11-15 10:06

@KeenLeung: 能不能一窥程序

@angelshelter:

import java.util.Date;

class BubbleSortApp {
public static void main(String[] args) {
for (int maxSize = 10000; maxSize <= 50000; maxSize += 10000) {
ArrayBub arr;
arr = new ArrayBub(maxSize);

for (int j = 0; j < maxSize; j++) {
long n = (long) (java.lang.Math.random() * (maxSize - 1));
arr.insert(n);
}
/*
* for(int j=maxSize-1;j>=0;j--){ arr.insert(j); }
*/

Date before = new Date();
// arr.display();
arr.bubbleSort();
// arr.display();
Date after = new Date();
long time = after.getTime() - before.getTime();
System.out.println("数组的个数" + " " + maxSize + " " + "冒泡排序时间为"
+ " " + time + "ms" + " " + "(随机)");
}
}
}

@angelshelter:

class ArrayBub {
private long[] a;
private int nElems;

public ArrayBub(int max) {
a = new long[max];
nElems = 0;
}

public void insert(long value) {
a[nElems] = value;
nElems++;
}

public void display() {
for (int j = 0; j < nElems; j++)
System.out.print(a[j] + " ");
System.out.println(" ");
}

public void bubbleSort() {
int out, in;
for (out = nElems - 1; out > 1; out--)
for (in = 0; in < out; in++)
if (a[in] > a[in + 1])
swap(in, in + 1);

}

public void swap(int one, int two) {
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}

}

@KeenLeung: 原因找到了

public void bubbleSort() {
int out, in;
for(out=0;out<nElems;out++)
for(in=1;in<nElems-out;in++)
if(a[in-1]>a[in])
swap(in-1,in);
}

@angelshelter:

数组大小            时间ms         交换次数

10^5               2067            100973415

10^6               4760            224607593

10^5                2491           199990000

10^6                 5350          449985000

您需要登录以后才能回答，未注册用户请先注册