-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInternalSort.cpp
More file actions
80 lines (73 loc) · 2.3 KB
/
Copy pathInternalSort.cpp
File metadata and controls
80 lines (73 loc) · 2.3 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
#include "TournamentTree.h"
#include<bits/stdc++.h>
#include <queue>
#include<iostream>
#include <bit>
#include"Disk.h"
#include "InternalSort.h"
#include"Sort.h"
int InternalSort::runNumber = 0;
Row senitnelRow; // Sentinel row used as a marker for the end of runs
// Function to generate a mini-run of size equal to the cache size
void generateCacheSizeRuns(vector<queue<Row>>&cacheSizeRuns, int &cnt) {
queue<Row> cacheSizeRun;
Tree::buildTree();
while(cacheSizeRun.size() < cnt) {
Row row = Tree::getWinner();
cacheSizeRun.push(row);
}
cacheSizeRun.push(senitnelRow);
cacheSizeRuns.push_back(cacheSizeRun);
SortPlan::runs = vector<queue<Row>>();
cnt = 0;
}
// Function for generating sorted runs from the data in memory
void InternalSort::generateRuns() {
TRACE(true);
SortPlan::runs = vector<queue<Row>>();
vector<int> sentinel_record(1, INT_MAX);
senitnelRow.record = sentinel_record;
int cnt = 0;
vector<queue<Row>>cacheSizeRuns;
queue<Row>cacheSizeRun;
int totalRecords = 0;
for(auto &page : Memory::buffer) {
for(auto row : page.rows) {
totalRecords++;
queue<Row>run;
run.push(row);
run.push(senitnelRow);
SortPlan::runs.push_back(run);
cnt++;
if(cnt == CACHE_SIZE) {
generateCacheSizeRuns(cacheSizeRuns, cnt);
}
}
}
if(cnt > 0) {
generateCacheSizeRuns(cacheSizeRuns, cnt);
}
//Merge cache size mini runs
SortPlan::runs = cacheSizeRuns;
int totalPages = (int)ceil((double)totalRecords/PAGE_SIZE);
Tree::buildTree();
Page outputPage; // take it from memory
string filename= "run_" + to_string(runNumber);
string filePath = SortPlan::pass_0_dirname+"/"+filename;
int pidx = 0;
cnt=0;
SortPlan::runPriority.push({totalPages, runNumber, 0});
while(cnt < totalRecords) {
Row row = Tree::getWinner();
cnt++;
outputPage.rows.push_back(row);
if(outputPage.rows.size() == PAGE_SIZE) {
Disk::flushPage(filePath, outputPage, pidx, 1);
}
}
// Flush any remaining rows in the output page
if(outputPage.rows.size() >0) {
Disk::flushPage(filePath, outputPage, pidx, 1);
}
runNumber++;
}