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