summaryrefslogtreecommitdiff
path: root/algo1w1/NAWOrderedArray.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'algo1w1/NAWOrderedArray.cpp')
-rw-r--r--algo1w1/NAWOrderedArray.cpp67
1 files changed, 67 insertions, 0 deletions
diff --git a/algo1w1/NAWOrderedArray.cpp b/algo1w1/NAWOrderedArray.cpp
new file mode 100644
index 0000000..6bce0cc
--- /dev/null
+++ b/algo1w1/NAWOrderedArray.cpp
@@ -0,0 +1,67 @@
+#include "NAWOrderedArray.h"
+#include "NAW.h"
+#include <iostream>
+#include <math.h>
+
+NAWOrderedArray::NAWOrderedArray() { }
+
+NAWOrderedArray::~NAWOrderedArray() { }
+
+int NAWOrderedArray::find(const NAW& naw) const {
+ unsigned tail = 0, head = _nawCollectionSize; // range is tail to head non-inclusive
+ unsigned max_attempts = log2(_nawCollectionSize) + 1; // return -1 infinite loop failsafe
+ for (unsigned x = 0; x < max_attempts; x++) {
+ unsigned guess = (head + tail) / 2; // take middle index
+ int diff = _nawCollection[guess]->compareTo(naw);
+ if (diff > 0) head = guess; // lower half (too high)
+ else if (diff < 0) tail = guess; // upper half (too low)
+ else return guess; // index found if compareTo(...) -> 0
+ }
+ return -1; // infinite loop failsafe
+}
+
+int NAWOrderedArray::add(const NAW& naw) {
+ int i;
+ // find insert index
+ for (i = 0; i < _nawCollectionSize; i++) {
+ if (_nawCollection[i]->compareTo(naw) > 0) break;
+ }
+ // shift elements
+ for (int k = _nawCollectionSize; k >= i; k--) {
+ if (k == 0) continue;
+ // std::cout << "moving [" << k-1 << "] to [" << k << "]" << std::endl;
+ _nawCollection[k] = _nawCollection[k-1];
+ }
+ _nawCollectionSize++;
+ // std::cout << "inserting into [" << i << "]" << std::endl;
+ _nawCollection[i] = new NAW(naw);
+ return i;
+}
+
+int NAWOrderedArray::remove(const NAW& naw) {
+ int i = find(naw);
+ // shift elements
+ for (int k = i; k < _nawCollectionSize; k++)
+ _nawCollection[k] = _nawCollection[k + 1];
+
+ _nawCollectionSize--;
+ return i;
+}
+
+int NAWOrderedArray::replace(const NAW& cOld, const NAW& cNew) {
+ bool opdrachtBeschrijvingIsDuidelijk = false; // true om de array opnieuw te sorteren na vervangen
+ int i = find(cOld);
+ if (i < 0) return -1;
+ if (opdrachtBeschrijvingIsDuidelijk == false) {
+ _nawCollection[i] = new NAW(cNew);
+ } else {
+ remove(cOld);
+ add(cNew);
+ }
+ return i;
+}
+
+void NAWOrderedArray::showAll() const {
+ for (unsigned i = 0; i < _nawCollectionSize; i++)
+ std::cout << *_nawCollection[i] << std::endl;
+}