빠 른 정렬. - 다 중 스 레 드 로 빠 른 정렬.

5129 단어 JAVA
package com.spark;

import org.junit.Before;
import org.junit.Test;
import scala.tools.nsc.Global;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by fanyuli on 2018/5/2.
 */
public class TestQuickSort {
    int index = -1;
    CountDownLatch countDownLatch = new CountDownLatch(2);
    int[] data = new int[800000];

    @Before
    public void initData() {
        Random r = new Random();
        for(int i=0;i<data.length;i++) {
           data[i] = r.nextInt(100);
        }
    }

    @Test
    public void testQuickSortThread() {  //        
        ExecutorService executorService = Executors.newFixedThreadPool(2);
      System.out.println(System.currentTimeMillis());

index = partition(
data,
0,
data.
length -
1); quickSortThread q1 =
new quickSortThread(
data,
0,
index -
1); quickSortThread q2 =
new quickSortThread(
data,
index +
1,
data.
length-
1); executorService.execute(q1); executorService.execute(q2);
try{
countDownLatch.await(); }
catch (Exception e) { e.printStackTrace(); }
for(
int i=
0;i <
data.
length;i++) {
//System.out.print(data[i] + "");
} System.
out.println(
"
\r
"+ System.
currentTimeMillis()); }
class quickSortThread
implements Runnable {
int
start;
int
end;
int[]
data;
public quickSortThread(
int[] data,
int start,
int end) {
this.
start = start;
this.
end = end;
this.
data = data; }
@Override
public void run() { quickSort(
data,
start,
end);
countDownLatch.countDown(); }
public void quickSort(
int[] data,
int left,
int right) {
if(left >= right)
return;
int i = partition(data,left,right); quickSort(data,left,i -
1); quickSort(data,i +
1,right); } }
@Test
public void runQuickSort () {/단일 스 레 드 로 정렬 시스템.
out.println(System.
currentTimeMillis()); quickSort(
data,
0,
data.
length -
1);
for(
int i=
0;i <
data.
length;i++) {
//System.out.print(data[i] + "");
} System.
out.println(
"
\r
"+ System.
currentTimeMillis()); }
public void quickSort(
int[] data,
int left,
int right) {
if(left >= right)
return;
index = partition(data,left,right); quickSort(data,left,
index -
1); quickSort(data,
index +
1,right); }
public int partition(
int[] data,
int left,
int right) {
int temp = data[left];
while(left < right) {
while(temp <= data[right] && left < right){ right--; } data[left] = data[right];
while(temp > data[left] && left < right){ left++; } data[right] = data[left]; } data[left] = temp;
return left; }}

좋은 웹페이지 즐겨찾기