1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 package org.slf4j.profiler;
26
27 import java.util.ArrayList;
28 import java.util.Arrays;
29
30 public class SortAndPruneComposites {
31
32 static String NESTED_PROFILER_NAME = "SORT_AND_PRUNE";
33
34 final int[] originalArray;
35 final int originalArrrayLength;
36
37 public SortAndPruneComposites(int[] randomArray) {
38 this.originalArray = randomArray;
39 this.originalArrrayLength = randomArray.length;
40
41 }
42
43 public int[] sortAndPruneComposites() {
44
45 ProfilerRegistry profilerRegistry = ProfilerRegistry.getThreadContextInstance();
46 Profiler sortProfiler = profilerRegistry.get(NESTED_PROFILER_NAME);
47
48
49 sortProfiler.start("SORT");
50 int[] sortedArray = sort();
51
52 sortProfiler.start("PRUNE_COMPOSITES");
53 int[] result = pruneComposites(sortedArray);
54
55 return result;
56 }
57
58 private int[] sort() {
59 int[] sortedArray = new int[originalArrrayLength];
60 System.arraycopy(originalArray, 0, sortedArray, 0, originalArrrayLength);
61 Arrays.sort(sortedArray);
62 return sortedArray;
63 }
64
65 int[] pruneComposites(int[] sortedArray) {
66 ArrayList<Integer> primesArray = new ArrayList<>();
67 for (int i = 0; i < originalArrrayLength; i++) {
68 int n = sortedArray[i];
69 if (isPrime(n)) {
70 primesArray.add(n);
71 }
72 }
73 int resultSize = primesArray.size();
74 int[] result = new int[resultSize];
75
76 for (int i = 0; i < resultSize; i++) {
77 result[i] = primesArray.get(i);
78 }
79 return result;
80 }
81
82 public boolean isPrime(int n) {
83 if (n < 2) {
84 return false;
85 }
86 if (n % 2 == 0) {
87 return false;
88 }
89 for (int i = 3; i * i <= n; i += 2) {
90 if (n % i == 0) {
91 return false;
92 }
93 }
94 return true;
95 }
96 }