Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Binary heap #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(heaps CXX)
set(CMAKE_CXX_STANDARD 17)

include(GNUInstallDirs)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_LIBDIR})
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/${CMAKE_INSTALL_BINDIR})

# we use this to get code coverage
if(CMAKE_CXX_COMPILER_ID MATCHES GNU)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fprofile-arcs -ftest-coverage")
endif()

add_subdirectory(src/BinaryHeap)

include(cmake/googletest.cmake)
fetch_googletest(
${PROJECT_SOURCE_DIR}/cmake
${PROJECT_BINARY_DIR}/googletest
)

enable_testing()
add_subdirectory(test)

20 changes: 20 additions & 0 deletions cmake/googletest-download.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# code copied from https://crascit.com/2015/07/25/cmake-gtest/
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(googletest-download NONE)

include(ExternalProject)

ExternalProject_Add(
googletest
SOURCE_DIR "@GOOGLETEST_DOWNLOAD_ROOT@/googletest-src"
BINARY_DIR "@GOOGLETEST_DOWNLOAD_ROOT@/googletest-build"
GIT_REPOSITORY
https://github.com/google/googletest.git
GIT_TAG
release-1.8.0
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
)
32 changes: 32 additions & 0 deletions cmake/googletest.cmake
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# the following code to fetch googletest
# is inspired by and adapted after https://crascit.com/2015/07/25/cmake-gtest/
# download and unpack googletest at configure time

macro(fetch_googletest _download_module_path _download_root)
set(GOOGLETEST_DOWNLOAD_ROOT ${_download_root})
configure_file(
${_download_module_path}/googletest-download.cmake
${_download_root}/CMakeLists.txt
@ONLY
)
unset(GOOGLETEST_DOWNLOAD_ROOT)

execute_process(
COMMAND
"${CMAKE_COMMAND}" -G "${CMAKE_GENERATOR}" .
WORKING_DIRECTORY
${_download_root}
)
execute_process(
COMMAND
"${CMAKE_COMMAND}" --build .
WORKING_DIRECTORY
${_download_root}
)

# adds the targers: gtest, gtest_main, gmock, gmock_main
add_subdirectory(
${_download_root}/googletest-src
${_download_root}/googletest-build
)
endmacro()
301 changes: 301 additions & 0 deletions src/BinaryHeap/BinaryHeap.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,301 @@
//
// Created by not sashka on 19.10.18.
//

#ifndef BINARY_HEAP_BINARYHEAP_H
#define BINARY_HEAP_BINARYHEAP_H

#include <cassert>
#include <cstring>
#include <memory>
#include <exception>
#include <bits/shared_ptr.h>
#include <cmath>
#include "Vector.hpp"

template<typename T>
class BinaryHeap {
private:
class Pointer;
public:
RunFMe marked this conversation as resolved.
Show resolved Hide resolved
bool empty();

size_t size();

size_t get_tree_degree();

std::shared_ptr<Pointer> insert(T value);

T min();

T extract_min();

T extract(std::shared_ptr<Pointer> pointer);

void change(std::shared_ptr<Pointer> pointer, T new_value);

BinaryHeap();

template<class Iterator>
BinaryHeap(Iterator begin, Iterator end);

void optimize(size_t insert_count, size_t extract_count) {
if (size() != 0) {
throw std::runtime_error("Can Not optimize non empty heap");
}
if (extract_count > insert_count) {
throw std::invalid_argument("Extract count can not be grater than insert count");
}
if (extract_count == 0) {
throw std::invalid_argument("Extract count can not be 0");
}

double alpha = 1.0 * insert_count / extract_count;
double prev_time_consumption = -1;
double time_consumption = -1;
unsigned long k = 1;

while (prev_time_consumption == -1 || time_consumption <= prev_time_consumption) {
++k;
prev_time_consumption = time_consumption;
time_consumption = (1.0 * k + alpha) / std::log(k);
}

tree_degree = k - 1;
}

private:
class Pointer {
public:
friend class BinaryHeap<T>;

Pointer(unsigned long index, BinaryHeap *parent_heap);

T value();

bool is_valid();

BinaryHeap *get_parent_heap();

private:
BinaryHeap *parent_heap;
unsigned long array_index;
bool valid;
};

struct Element {
T value;
std::shared_ptr<typename BinaryHeap<T>::Pointer> pointer;
};

size_t tree_degree = 2;
Vector<Element> storage;

void swap_elements(unsigned long first_index, unsigned long second_index);

unsigned long parent(unsigned long index);

unsigned long nth_child(unsigned long index, unsigned long n);

void sift_up(unsigned long index);

void sift_down(unsigned long index);

std::shared_ptr<Pointer> push_back_element(T value);
};

template<typename T>
BinaryHeap<T>::BinaryHeap() = default;

template<typename T>
template<class Iterator>
BinaryHeap<T>::BinaryHeap(Iterator begin, Iterator end) {
for (Iterator iter = begin; iter != end; ++iter) {
push_back_element(*iter);
}

//call sift_down for all non leaves
for (unsigned long i = size() / 2; i > 0; --i) {
sift_down(i - 1);
}
}

template<typename T>
size_t BinaryHeap<T>::size() {
return storage.size();
}

template<typename T>
bool BinaryHeap<T>::empty() {
return storage.empty();
}

template<typename T>
size_t BinaryHeap<T>::get_tree_degree() {
return tree_degree;
}

template<typename T>
std::shared_ptr<typename BinaryHeap<T>::Pointer> BinaryHeap<T>::insert(T value) {
auto pointer = push_back_element(value);
sift_up(pointer->array_index);
return pointer;
}

template<typename T>
T BinaryHeap<T>::min() {
if (empty()) {
throw std::runtime_error("No minimal element. Heap is empty.");
}
return storage[0].value;
}

template<typename T>
T BinaryHeap<T>::extract(std::shared_ptr<BinaryHeap::Pointer> pointer) {
if (!pointer->is_valid()) {
throw std::runtime_error("Invalidated pointer to an element");
}
if (pointer->get_parent_heap() != this) {
throw std::runtime_error("Pointer from another heap");
}

unsigned long extract_index = pointer->array_index;
T value = pointer->value();

//try to swap extracted with last element and sift it down
if (extract_index == size() - 1) {
storage.pop_back();
} else {
swap_elements(extract_index, size() - 1);
storage.pop_back();
sift_down(extract_index);
}

pointer->valid = false;
return value;
}

template<typename T>
T BinaryHeap<T>::extract_min() {
if (empty()) {
throw std::runtime_error("No minimal element. Heap is empty.");
}
return extract(storage[0].pointer);
}

template<typename T>
void BinaryHeap<T>::change(std::shared_ptr<BinaryHeap::Pointer> pointer, T new_value) {
if (!pointer->is_valid()) {
throw std::runtime_error("Invalidated pointer to an element");
}
if (pointer->get_parent_heap() != this) {
throw std::runtime_error("Pointer from another heap");
}

T previous_value = pointer->value();
storage[pointer->array_index].value = new_value;

if (new_value > previous_value) {
sift_down(pointer->array_index);
} else {
sift_up(pointer->array_index);
}
}

template<typename T>
void BinaryHeap<T>::swap_elements(unsigned long first_index, unsigned long second_index) {
if (first_index >= size() || second_index >= size()) {
throw std::out_of_range("At least one of indexes is out of range");
}
std::swap(storage[first_index].value, storage[second_index].value);
std::swap(storage[first_index].pointer->array_index, storage[second_index].pointer->array_index);
std::swap(storage[first_index].pointer, storage[second_index].pointer);
}

template<typename T>
std::shared_ptr<typename BinaryHeap<T>::Pointer> BinaryHeap<T>::push_back_element(T value) {
unsigned long new_index = storage.size();
std::shared_ptr<Pointer> pointer(new Pointer(new_index, this));
storage.push_back({value, pointer});

return pointer;
}

template<typename T>
void BinaryHeap<T>::sift_down(unsigned long index) {
if (index >= size()) {
throw std::out_of_range("Index is out of range");
}
unsigned long min_index = index;

for (unsigned long i = 0; i < tree_degree; ++i) {
unsigned long child_index = nth_child(index, i);
if (child_index < size() && storage[child_index].value < storage[min_index].value) {
min_index = child_index;
}
}

if (min_index != index) {
swap_elements(min_index, index);
sift_down(min_index);
}
}

template<typename T>
void BinaryHeap<T>::sift_up(unsigned long index) {
if (index >= size()) {
throw std::out_of_range("Index is out of range");
}
unsigned long current = index;

while (current != 0) {
unsigned long current_parent = parent(current);
if (storage[current].value < storage[current_parent].value) {
swap_elements(current, current_parent);
}
current = current_parent;
}
}

template<typename T>
unsigned long BinaryHeap<T>::nth_child(unsigned long index, unsigned long n) {
if (index >= size()) {
throw std::out_of_range("Index is out of range");
}
return index * tree_degree + n + 1;
}

template<typename T>
unsigned long BinaryHeap<T>::parent(unsigned long index) {
if (index == 0) {
throw std::runtime_error("Root node has no parent");
}
if (index >= size()) {
throw std::out_of_range("Index is out of range");
}
return (index - 1) / tree_degree;
}

template<typename T>
bool BinaryHeap<T>::Pointer::is_valid() {
return valid;
}

template<typename T>
T BinaryHeap<T>::Pointer::value() {
return parent_heap->storage[array_index].value;
}

template<typename T>
BinaryHeap<T>::Pointer::Pointer(unsigned long index, BinaryHeap *const parent_heap) {
this->array_index = index;
this->parent_heap = parent_heap;
this->valid = true;
}

template<typename T>
BinaryHeap<T> *BinaryHeap<T>::Pointer::get_parent_heap() {
return parent_heap;
}

#endif //BINARY_HEAP_BINARYHEAP_H
Loading