冒泡排序:
class BubbleSort {
public void sort(int[] array) {
for (int i = 1; i < array.length; i++) {
for (int j = 0; j < array.length - 1; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
}
}
快速排序
class Buicksort {
public int data[];
private int partition(int sortArray[], int low, int hight)
{
int key = sortArray[low];
while (low < hight)
{
while (low < hight && sortArray[hight] >= key)
hight--;
sortArray[low] = sortArray[hight];
while (low < hight && sortArray[low] <= key)
low++;
sortArray[hight] = sortArray[low];
}
sortArray[low] = key;
return low;
}
public void sort(int low, int hight)
{
if (low < hight)
{
int result = partition(data, low, hight);
sort(low, result - 1);
sort(result + 1, hight);
}
}
public void display()
{
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i]);
System.out.print(" ");
}
}
}
测试main函数:
BubbleSort bubbleSort = new BubbleSort();
int[] array = {44,22,2,32,54,22,88,77,99,11};
long t1 = System.currentTimeMillis();
bubbleSort.sort(array);
for (int i = 0; i < array.length; i++) {
System.out.print(array[i]);
System.out.print(" ");
}
long t2 = System.currentTimeMillis();
System.out.println(t2-t1);
System.out.println("\n--------------------------");
Buicksort buicksort = new Buicksort();
int data[] = {44,22,2,32,54,22,88,77,99,11};
buicksort.data = data;
long t3 = System.currentTimeMillis();
buicksort.sort(0, buicksort.data.length-1);
buicksort.display();
long t4 = System.currentTimeMillis();
System.out.println(t4-t3);
System.out.println("\n--------------------------");
int arraydata[] = {44,22,2,32,54,22,88,77,99,11};
long t5 = System.currentTimeMillis();
Arrays.sort(arraydata);
for (int i = 0; i < array.length; i++) {
System.out.print(arraydata[i]);
System.out.print(" ");
}
long t6 = System.currentTimeMillis();
System.out.println(t6-t5);
通过运行结果得出:还是jdk自带的方法运行效果最高!