1
+ /**
2
+ * Hackerrank
3
+ * In this challenge, print your array every time your partitioning method
4
+ * finishes, i.e. whenever two subarrays, along with the pivot, are merged
5
+ * together. The first element in a sub-array should be used as a pivot.
6
+ * Partition the left side before partitioning the right side.
7
+ * The pivot should be placed between sub-arrays while merging them.
8
+ * Array of length or less will be considered sorted, and there is no need to
9
+ * sort or to print them.
10
+ *
11
+ * Constraints:
12
+ * 1. 1 <= n <= 1000
13
+ * 2. -1000 <= x <= 1000, x ∈ arr
14
+ * 3. All the characters in the sequence: {, }, [, ], (, )
15
+ *
16
+ * This solution got 30 points
17
+ * Problem link: http://hr.gs/fffdff
18
+ */
19
+
20
+ /**
21
+ *
22
+ * @param {string } input Custom input of Hackerrank
23
+ */
24
+ function processData ( input ) {
25
+ const arr = input . split ( '\n' ) [ 1 ]
26
+ . split ( ' ' )
27
+ . map ( el => + el ) ;
28
+ if ( arr . length < 2 ) {
29
+ return ;
30
+ }
31
+ quickSort ( arr ) ;
32
+ }
33
+
34
+ /**
35
+ *
36
+ * @param {number[] } arr The array/subarray to be sorted
37
+ */
38
+ function quickSort ( arr ) {
39
+ if ( arr . length > 1 ) {
40
+ let left = [ ] ;
41
+ let right = [ ] ;
42
+ const pivot = arr [ 0 ] ;
43
+ partition ( arr . slice ( 1 ) , left , right , pivot ) ;
44
+ left = quickSort ( left ) ;
45
+ right = quickSort ( right ) ;
46
+ const merged = [ ...left , pivot , ...right ]
47
+ console . log ( merged . join ( ' ' ) ) ;
48
+ return merged ;
49
+ } else {
50
+ return arr ;
51
+ }
52
+ }
53
+
54
+ /**
55
+ *
56
+ * @param {number[] } arr Original array
57
+ * @param {number[] } left All numbers lower than pivot will be placed here
58
+ * @param {number[] } right All numbers greater or queal than pivot will be placed here
59
+ * @param {number } pivot
60
+ */
61
+ function partition ( arr , left , right , pivot ) {
62
+ arr . forEach ( el => {
63
+ if ( el >= pivot ) {
64
+ right . push ( el ) ;
65
+ } else {
66
+ left . push ( el ) ;
67
+ }
68
+ } ) ;
69
+ }
70
+
71
+ /* In place
72
+ function quickSort(arr, low, high) {
73
+ if (low < high) {
74
+ const sortedIdx = partition(arr, low, high);
75
+ quickSort(arr, low, sortedIdx - 1);
76
+ quickSort(arr, sortedIdx + 1, high);
77
+ }
78
+ }
79
+ */
80
+ /* in place
81
+ function partition(arr, low, high) {
82
+ let i = low;
83
+ let j = high;
84
+ const pivot = low;
85
+ while (i < j) {
86
+ while(arr[i] <= arr[pivot]) {
87
+ i++;
88
+ }
89
+ while(arr[j] > arr[pivot]) {
90
+ j--;
91
+ }
92
+ if (i < j) {
93
+ const iVal = arr[i];
94
+ arr[i] = arr[j];
95
+ arr[j] = iVal;
96
+ }
97
+ }
98
+ const copy = arr[pivot];
99
+ arr[pivot] = arr[j];
100
+ arr[j] = copy;
101
+ return j;
102
+ }
103
+ */
0 commit comments