-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaletta.cpp
More file actions
84 lines (63 loc) · 1.94 KB
/
paletta.cpp
File metadata and controls
84 lines (63 loc) · 1.94 KB
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <algorithm>
#include <vector>
using namespace std;
#include <iostream>
#include <vector>
long long mergeAndCount(std::vector<int>& arr, int left, int mid, int right) {
std::vector<int> leftArr(arr.begin() + left, arr.begin() + mid + 1);
std::vector<int> rightArr(arr.begin() + mid + 1, arr.begin() + right + 1);
int i = 0, j = 0, k = left;
long long swaps = 0;
while (i < leftArr.size() && j < rightArr.size()) {
if (leftArr[i] <= rightArr[j]) {
arr[k++] = leftArr[i++];
} else {
arr[k++] = rightArr[j++];
swaps += leftArr.size() - i; // elementi rimanenti a sinistra > elemento a destra
}
}
while (i < leftArr.size()) {
arr[k++] = leftArr[i++];
}
while (j < rightArr.size()) {
arr[k++] = rightArr[j++];
}
return swaps;
}
long long mergeSortAndCount(std::vector<int>& arr, int left, int right) {
long long swaps = 0;
if (left < right) {
int mid = left + (right - left) / 2;
swaps += mergeSortAndCount(arr, left, mid);
swaps += mergeSortAndCount(arr, mid + 1, right);
swaps += mergeAndCount(arr, left, mid, right);
}
return swaps;
}
long long paletta_sort(int N, int V[]) {
// vector<int> index(N);
vector<int> odd (N/2 + N%2);
vector<int> even (N/2);
// verifica parità
for (int i=0; i<N; i++) {
if (V[i] % 2 != i % 2) return -1;
// index[V[i]] = i;
if (V[i] % 2) {
even[i/2] = V[i];
} else {
odd[i/2] = V[i];
}
}
long long count = 0;
// sorting
/*for (int i=0; i<N; i++) {
long long j = index[i];
while (j >= i + 2) {
swap (V[j], V[j-2]);
swap (index[V[j]], index[V[j-2]]);
count ++;
j -= 2;
}
}*/
return mergeSortAndCount(odd, 0, odd.size()-1) + mergeSortAndCount(even, 0, even.size()-1);
}