Пример #1
0
def k_sorted_array(arr, k):
    """ Method sorts a k-sorted array.

    A k-sorted array is an array where each element is at most k positions away
    of it's final sorted position.

    This solution piggybacks on the heapsort algorithm

    Complexity: O(nlogk) in time

    Args:
        arr: list, of values to sort.
        k: int, the max distance any element can be from it's final sorted position.

    Returns:
        list, sorted array
    """
    n = len(arr)
    if n < k:
        k = n

    heap = Heap.heapify(arr[:k])

    out = []
    for i in range(k, n):
        min_value = heap.extract_min_and_insert(arr[i])
        out.append(min_value)

    for i in range(k):
        min_value = heap.extract_min()
        out.append(min_value)

    return out
Пример #2
0
 def test_heap_length(self):
     data = [1, 2, 3, 114, 5, 6, 7, 8, 9, 10]
     h = Heap.heapify(data)
     self.assertEqual(len(h), len(data), 'should be the same length')
Пример #3
0
 def test_heap_length(self):
     data = [1,2,3,114,5,6,7,8,9,10]
     h = Heap.heapify(data)
     self.assertEqual(len(h), len(data), 'should be the same length')
Пример #4
0
 def test_static_heapify(self):
     data = [8, 2, 6, 3, 1, 2, 9, 5, 3, 7, 4]
     h = Heap.heapify(data)
     self.assertTrue(Heap.is_heap(data), 'should preserve heap property')
Пример #5
0
 def test_static_heapify(self):
     data = [8,2,6,3,1,2,9,5,3,7,4]
     h = Heap.heapify(data)
     self.assertTrue(Heap.is_heap(data), 'should preserve heap property')