private double updateMedian(int number, double prevMedian, MaxHeap maxHeap, MinHeap minHeap) { int minCount = minHeap.GetCount(); int maxCount = maxHeap.GetCount(); if (maxCount > minCount) { if (number < prevMedian) { minHeap.Insert(maxHeap.ExtractTop()); maxHeap.Insert(number); } else { minHeap.Insert(number); } return 0.5 * (minHeap.GetTop() + maxHeap.GetTop()); } if (minCount == maxCount) { if (number < prevMedian) { maxHeap.Insert(number); return maxHeap.GetTop(); } else { minHeap.Insert(number); return minHeap.GetTop(); } } if (maxCount < minCount) { if (number < prevMedian) { maxHeap.Insert(number); } else { maxHeap.Insert(minHeap.ExtractTop()); minHeap.Insert(number); } return 0.5 * (minHeap.GetTop() + maxHeap.GetTop()); } return -1; }
public MedianUnique(string inputFile, string outputFile) { int nUniqueWords = 0; double prevMedian = 0; List<double> medianValues = new List<double>(); string line; StreamReader tweetInput = new StreamReader(inputFile); StreamWriter tweetOutput = new StreamWriter(outputFile); var minHeap = new MinHeap(); var maxHeap = new MaxHeap(); bool firstPass = true; while (( line = tweetInput.ReadLine()) != null) { nUniqueWords = this.processLine(line); if (firstPass) { prevMedian = nUniqueWords; } prevMedian = updateMedian(nUniqueWords,prevMedian, maxHeap, minHeap); medianValues.Add(prevMedian); tweetOutput.WriteLine(prevMedian); } tweetInput.Close(); tweetOutput.Close(); }