我比较了快速排序(普通,递归)和线程快速排序(使用线程)。我发现普通快速排序比线程快速排序快。是这样吗?我觉得我做错了什么。
代码如下:
public class QuickSort implements SortAlgorithm {
public void Sort(Integer[] array) {
Sort(array, 0, array.length-1);
}
private void Sort(Integer[] array, Integer low, Integer high) {
if (low < high) {
Integer pivot = partition(array, low, high);
Sort(array, low, pivot-1);
Sort(array, pivot+1, high);
}
}
private Integer partition(Integer[] array, Integer low, Integer high) {
Integer pivot = array[high];
Integer i = (low-1);
for (Integer j=low; j<high; j++)
if (array[j] < pivot) {
i++;
Integer temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Integer temp = array[i+1];
array[i+1] = array[high];
array[high] = temp;
return i+1;
}
}
public class ThreadsQuickSort extends Thread implements SortAlgorithm {
private Integer low, high;
private Integer[] array;
public ThreadsQuickSort() {
;
}
public ThreadsQuickSort(Integer[] array, Integer low, Integer high) {
this.array = array;
this.low = low;
this.high = high;
}
public void run() {
Sort(array, low, high);
}
public void Sort(Integer[] array) {
Sort(array, 0, array.length - 1);
}
private void Sort(Integer[] array, Integer low, Integer high) {
if (low < high) {
Integer pivot = partition(array, low, high);
ThreadsQuickSort lowQSort = new ThreadsQuickSort(array, low, pivot - 1);
lowQSort.start();
ThreadsQuickSort highQSort = new ThreadsQuickSort(array, pivot + 1, high);
highQSort.start();
try {
lowQSort.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
highQSort.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Integer partition(Integer[] array, Integer low, Integer high) {
Integer pivot = array[high];
Integer i = (low-1);
for (Integer j=low; j<high; j++)
if (array[j] < pivot) {
i++;
Integer temp = array[i];
array[i] = array[j];
array[j] = temp;
}
Integer temp = array[i+1];
array[i+1] = array[high];
array[high] = temp;
return i+1;
}
}
main函数使用这两种算法对10000个项目的数组进行排序,并获得它们的执行时间。获得以下输出:
Single array sorted in 11 ms
The array was successfully sorted
Threaded array sorted in 6378 ms
The array was successfully sorted
我的问题是,这是否是良好的编码和输出是预期的。这与线程化快速排序的实现无关。
1条答案
按热度按时间62lalag41#
每个线程大约70个微创建和开关。
螺纹的总和应在20000-1左右,即20000*70us=140000us=1400ms=1.4s
因此,这接近预期。