TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
library_sort.cpp
1#include <algorithm>
2#include <iostream>
3
4void librarySort(int *index, int n) {
5 int lib_size, index_pos,
6 *gaps, // gaps
7 *library[2]; // libraries
8
9 bool target_lib, *numbered;
10
11 for (int i = 0; i < 2; i++) library[i] = new int[n];
12
13 gaps = new int[n + 1];
14 numbered = new bool[n + 1];
15
16 lib_size = 1;
17 index_pos = 1;
18 target_lib = 0;
19 library[target_lib][0] = index[0];
20
21 while (index_pos < n) {
22 // binary search
23 int insert = std::distance(
24 library[target_lib],
25 std::lower_bound(library[target_lib],
26 library[target_lib] + lib_size, index[index_pos]));
27
28 // if there is no gap to insert a new index ...
29
30 if (numbered[insert] == true) {
31 int prov_size = 0, next_target_lib = !target_lib;
32
33 // update library and clear gaps
34
35 for (int i = 0; i <= n; i++) {
36 if (numbered[i] == true) {
37 library[next_target_lib][prov_size] = gaps[i];
38 prov_size++;
39 numbered[i] = false;
40 }
41
42 if (i <= lib_size) {
43 library[next_target_lib][prov_size] =
44 library[target_lib][i];
45 prov_size++;
46 }
47 }
48
49 target_lib = next_target_lib;
50 lib_size = prov_size - 1;
51 } else {
52 numbered[insert] = true;
53 gaps[insert] = index[index_pos];
54 index_pos++;
55 }
56 }
57
58 int index_pos_for_output = 0;
59 for (int i = 0; index_pos_for_output < n; i++) {
60 if (numbered[i] == true) {
61 // std::cout << gaps[i] << std::endl;
62 index[index_pos_for_output] = gaps[i];
63 index_pos_for_output++;
64 }
65
66 if (i < lib_size) {
67 // std::cout << library[target_lib][i] << std::endl;
68 index[index_pos_for_output] = library[target_lib][i];
69 index_pos_for_output++;
70 }
71 }
72 delete[] numbered;
73 delete[] gaps;
74 for (int i = 0; i < 2; ++i) {
75 delete[] library[i];
76 }
77}
78
79int main() {
80 // ---example--
81 int index_ex[] = {-6, 5, 9, 1, 9, 1, 0, 1, -8, 4, -12};
82 int n_ex = sizeof(index_ex) / sizeof(index_ex[0]);
83
84 librarySort(index_ex, n_ex);
85 std::cout << "sorted array :" << std::endl;
86 for (int i = 0; i < n_ex; i++) std::cout << index_ex[i] << " ";
87 std::cout << std::endl;
88
89 /* --output--
90 sorted array :
91 -12 -8 -6 0 1 1 1 4 5 9 9
92 */
93}
node * insert(node *root, int item)
inserts a new element into AVL tree
Definition avltree.cpp:92
int main()
Main function.