fix(learn): isSorted returning true on empty arrays which passes the test (#40192)

* bug-fix: isSorted returning true on empty arrays

* sorted order test improvements
This commit is contained in:
Farhan Ullah
2020-11-20 22:51:59 +05:00
committed by GitHub
parent f4fe5a183b
commit 9ba94e38b4

View File

@ -30,7 +30,30 @@ tests:
- text: MinHeap should have a method called sort. - text: MinHeap should have a method called sort.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; return (typeof test.sort == 'function')})()); testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; return (typeof test.sort == 'function')})());
- text: The sort method should return an array containing all items added to the min heap in sorted order. - text: The sort method should return an array containing all items added to the min heap in sorted order.
testString: assert((function() { var test = false; if (typeof MinHeap !== 'undefined') { test = new MinHeap() } else { return false; }; test.insert(3); test.insert(12); test.insert(5); test.insert(10); test.insert(1); test.insert(27); test.insert(42); test.insert(57); test.insert(5); var result = test.sort(); return (isSorted(result)); })()); testString: |+
assert((() => {
if (typeof MinHeap === "undefined") {
return false;
}
const heap = new MinHeap();
const arr = createRandomArray(25);
for (let i of arr) {
heap.insert(i);
}
const result = heap.sort();
arr.sort((a, b) => a - b);
for (let i = 0; i < arr.length; i++) {
if (arr[i] !== result[i]) {
return false;
}
}
return true;
})());
``` ```
</section> </section>
@ -48,11 +71,15 @@ function isSorted(a){
return true; return true;
} }
// Generate a randomly filled array // Generate a randomly filled array
var array = new Array(); function createRandomArray(size = 5){
(function createArray(size = 5) { let a = new Array(size);
array.push(+(Math.random() * 100).toFixed(0)); for(let i = 0; i < size; i++)
return size > 1 ? createArray(size - 1) : undefined; a[i] = Math.floor(Math.random() * 100);
})(25);
return a;
}
const array = createRandomArray(25);
var MinHeap = function() { var MinHeap = function() {
// Only change code below this line // Only change code below this line