快速排序算法

来源:互联网 发布:摩比神奇 知乎 编辑:程序博客网 时间:2024/06/05 09:18

基本思想:

选取一个值作为参考值,通过变换最终使参考值左边的数都小于等于它,右边的值都大于它


步骤: 假设数组为toSort,开始坐标为start,结束坐标为end,选取start坐标的值作为参考值。

1.选取参考值refer为toSort[start].

2.从数组的end处向start处遍历数组,找到小于refer的值的坐标k.

3.将toSort[k]赋值给toSort[start].

4.从数组的start处向end处遍历数组,找到大于refer的值的坐标j.

5.将toSort[j]赋值给toSort[k].

6.从k处向start处遍历数组,重复2到5的步骤(第四步从j处向end处遍历数组)直到k=j.

7.将refer的值赋给toSort[j].

8.以j为边界将数组分为左右两边,依次进行快速排序


代码:

1.单线程

import java.util.Arrays;
public class Quick{
private int[] toSort = {2,15,14,32,42,9,51,32,28,4,3,66,8,6,74,36,97,10,11,58,5,88,46,41,7,1,16,19,44,99};


public void quickSort(int start, int end) {
if(start < end) {
int i = start;
int j = end;
int refer = toSort[start];
while(start < end) {
while(toSort[end] > refer && start < end) {
end--;
}
if(end > start) {
toSort[start++] = toSort[end];
}
while(toSort[start] <= refer && start < end) {
start++;
}
if(start < end) {
toSort[end--] = toSort[start];
}
}
toSort[start] = refer;
quickSort(i, start - 1);
quickSort(start + 1, j);
}
}


public static void main(String[] args) {
Quick target = new Quick();
long startTime = System.nanoTime();
target.quickSort(0,target.toSort.length - 1);
long endTime = System.nanoTime();
System.out.println(Arrays.toString(target.toSort));
System.out.println("total time is:" + (endTime - startTime) + "ns");
}
}


2.多线程

import java.util.concurrent.RecursiveAction;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ForkJoinPool;
import java.util.Arrays;


public class QuickSort_ForkJoinPool{
private int[] toSort = {2,15,14,32,42,9,51,32,28,4,3,66,8,6,74,36,97,10,11,58,5,88,46,41,7,1,16,19,44,99};


public void quickSort(int start, int end) {
if(start < end) {
int i = start;
int j = end;
int refer = toSort[start];
while(start < end) {
while(toSort[end] > refer && start < end) {
end--;
}
if(end > start) {
toSort[start++] = toSort[end];
}
while(toSort[start] <= refer && start < end) {
start++;
}
if(start < end) {
toSort[end--] = toSort[start];
}
}
toSort[start] = refer;
new SortTask(i, start - 1).fork();
new SortTask(start + 1, j).fork();
}
}


public static void main(String[] args) throws InterruptedException{
QuickSort_ForkJoinPool target = new QuickSort_ForkJoinPool();
ForkJoinPool threadPool = new ForkJoinPool();
RecursiveAction task = target.new SortTask(0,target.toSort.length - 1);
long startTime = System.nanoTime();
threadPool.submit(task);
threadPool.awaitTermination(2, TimeUnit.SECONDS);
long endTime = System.nanoTime();
threadPool.shutdown();
System.out.println(Arrays.toString(target.toSort));
System.out.println("total time is:" + (endTime - startTime) + "ns");
}


private class SortTask extends RecursiveAction{
private int start;
private int end;
public SortTask(int start, int end) {
this.start = start;
this.end = end;
}
@Override
protected void compute() {
QuickSort_ForkJoinPool.this.quickSort(start, end);
}
}
}

原创粉丝点击