%%QuickInterview 
  
%

%%Question
Input [num]
FilteredMedian [num]
%

%%Variable 
  FilteredMedian = topQuartilMedian(Input[num])
%

%%Function 
function topQuartilMedian(history) {
	return computeMedian(topQuartil(history);
}

function topQuartil(history) {
	return history.sort().slice(history.length * 0.75, history.length)
}

function computeMedian(a) {
	var low = 0;
	var high = a.length - 1;
	var median = (low + high) / 2;
	do {
		if (high <= low) {
			return a[median];
		}
		if (high == low + 1) {
			if (a[low] > a[high]) {
				swap(a, low, high);
			}
			return a[median];
		}
		var middle = (low + high) / 2;
		if (a[middle] > a[high]) {
			swap(a, middle, high);
		}
		if (a[low] > a[high]) {
			swap(a, low, high);
		}
		if (a[middle] > a[low]) {
			swap(a, middle, low);
		}
		swap(a, middle, low + 1);
		var ll = low + 1;
		var hh = high;
		do {
			do {
				ll++;
			} while (a[low] > a[ll]);
			do {
				hh--;
			} while (a[hh] > a[low]);
			if (hh < ll) {
				break;
			}
			swap(a, ll, hh);
		} while (true);
		swap(a, low, hh);
		if (hh <= median) {
			low = ll;
		}
		if (hh >= median) {
			high = hh - 1;
		}
	} while (true);
}

private static void swap(a, i1, i2) {
	var temp = a[i1];
	a[i1] = a[i2];
	a[i2] = temp;
}
	
@export: topQuartilMedian(HISTORY_NUMBER) -> NUMBER
%

%%KnowledgeBase 
DemoKB
%

%%Package filteredMedian2