输入一组数据然后java多线程快速排序
时间: 2023-07-01 07:26:37 浏览: 95
好的,下面是一个示例代码,可以让用户输入一组数据,然后使用Java多线程快速排序进行排序。
```java
import java.util.Scanner;
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入一组数据,以逗号分隔:");
String input = scanner.nextLine();
String[] strArray = input.split(",");
int[] array = new int[strArray.length];
for (int i = 0; i < array.length; i++) {
array[i] = Integer.parseInt(strArray[i]);
}
quickSort(array);
System.out.println("排序后的结果为:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void quickSort(int[] array) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new QuickSortTask(array, 0, array.length - 1));
executor.shutdown();
try {
executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static class QuickSortTask implements Runnable {
private int[] array;
private int left;
private int right;
public QuickSortTask(int[] array, int left, int right) {
this.array = array;
this.left = left;
this.right = right;
}
@Override
public void run() {
if (left >= right) {
return;
}
int i = left;
int j = right;
int pivot = array[(left + right) / 2];
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (left < j) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new QuickSortTask(array, left, j));
executor.shutdown();
}
if (i < right) {
ExecutorService executor = Executors.newCachedThreadPool();
executor.execute(new QuickSortTask(array, i, right));
executor.shutdown();
}
}
}
}
```
用户可以输入一组数据,然后程序将数据转换为整数数组,并使用Java多线程快速排序进行排序。最后输出排序结果。注意,在使用线程池时,需要在排序完成之前等待线程池中所有线程执行结束。
阅读全文