MergeSort.js
var merge_sort = function(unsorted) {
if (unsorted.length <= 1)
return unsorted;
var middle = unsorted.length / 2;
var left = unsorted.slice(0, middle - 1);
var right = unsorted.slice(middle, unsorted - 1);
left = merge_sort(left);
right = merge_sort(right);
return merge(left, right);
};
var merge = function(left, right) {
var result = [];
while(left.length > 0 || right.length > 0)
if(left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
} else if(left.length > 0) {
result.push(left.shift());
} else if(right.length > 0) {
result.push(right.shift());
}
}
return result;
};
MergeSortSpec.js
describe("#merge_sort", function() {
it("should sort the unsorted array", function() {
var unsorted = [8, 2, 10, 5, 4, 9, 7, 1, 6, 3];
var sorted = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
expect(merge_sort(unsorted)).toEqual(sorted);
});
});
错误消息
ReferenceError: merge_sort is not defined
at null.<anonymous> (file://localhost/Users/jasonkim/projects/algorithm-everyday/merge_sort/javascript/spec/MergeSortSpec.js:6:12)
我不确定为什么jasmine.js告诉我merge_sort
没有定义。即使它在那里。知道为什么吗?
SpecRunner.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Jasmine Spec Runner</title>
<link rel="shortcut icon" type="image/png" href="lib/jasmine-1.3.1/jasmine_favicon.png">
<link rel="stylesheet" type="text/css" href="lib/jasmine-1.3.1/jasmine.css">
<script type="text/javascript" src="lib/jasmine-1.3.1/jasmine.js"></script>
<script type="text/javascript" src="lib/jasmine-1.3.1/jasmine-html.js"></script>
<!-- include source files here... -->
<script type="text/javascript" src="src/MergeSort.js"></script>
<!-- include spec files here... -->
<script type="text/javascript" src="spec/MergeSortSpec.js"></script>
<script type="text/javascript">
(function() {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function(spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function() {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();
</script>
</head>
<body>
</body>
</html>
答案 0 :(得分:0)
问题可能是while
循环开始时缺少的开括号?如果你修复它,它在茉莉花中运行良好(尽管输出不正确)
var merge = function(left, right) {
var result = [];
while(left.length > 0 || right.length > 0) {
if(left.length > 0 && right.length > 0) {
if (left[0] <= right[0]) {
result.push(left.shift());
} else {
result.push(right.shift());
}
} else if(left.length > 0) {
result.push(left.shift());
} else if(right.length > 0) {
result.push(right.shift());
}
}
return result;
};