Skip to content

Latest commit

 

History

History
65 lines (49 loc) · 2.35 KB

69.md

File metadata and controls

65 lines (49 loc) · 2.35 KB

Java 8 - 数组并行排序

原文: https://beginnersbook.com/2017/10/java-8-arrays-parallel-sort-with-example/

Java 8 在java.util包的Arrays类中引入了一个新方法parallelSort()。引入此方法以支持数组元素的并行排序。 并行排序算法:

  1. 将给定的数组划分为子数组,将子数组进一步划分为子数组,直到子数组达到最小粒度为止。
  2. 子数组由多个线程单独排序。并行排序使用 Fork / Join Framework 并行地对子数组进行排序。
  3. 已合并的已排序子数组。

并行排序优于简单排序的优点:

parallelSort()方法使用多线程的概念,与正常排序相比,有很多元素时它更快。

示例 1:对原始数据类型进行并行排序

import java.util.Arrays; 
public class Example {  
   public static void main(String[] args) {
	int numbers[] = {22, 89, 1, 32, 19, 5};
	//Parallel Sort method for sorting int array
	Arrays.parallelSort(numbers);
	//converting the array to stream and displaying using forEach
	Arrays.stream(numbers).forEach(n->System.out.print(n+" "));
    }
}

输出:

1 5 19 22 32 89

参考文献:

Java 8 - 并行排序 JavaDoc

示例 2:通过指定开始和结束索引进行并行排序

我们还可以指定排序的开始和结束,在这种情况下,从开始索引开始并在结束索引结束的子数组被排序,数组的其余部分被忽略并且不被排序。

import java.util.Arrays; 
public class Example {  
   public static void main(String[] args) {
	int numbers[] = {22, 89, 1, 32, 19, 5};
	/* Specifying the start and end index. The start index is
	 * 1 here and the end index is 5\. which means the the elements
	 * starting from index 1 till index 5 would be sorted.
	 */
	Arrays.parallelSort(numbers, 1, 5);
	//converting the array to stream and displaying using forEach
	Arrays.stream(numbers).forEach(n->System.out.print(n+" "));
   }
}

输出:

22 1 19 32 89 5