我在我的quickSort函式中收到以下錯誤訊息:
型別錯誤:陣列未定義
如何quickSort使用下面定義的原型撰寫函式ArrayList?
function ArrayList() {
this.items = [];
}
ArrayList.prototype.insert = function(item) {
this.items.push(item);
}
ArrayList.prototype.toString = function() {
return this.items.join();
}
//This is a function to create a non sorted array using the array function above
function createNonSortedRandomArray(size) {
var elements = size;
var array = new ArrayList();
for (var i = elements; i > 0; i--) {
array.insert(i);
}
return array;
}
swap = function(array, index1, index2) {
var aux = array[index1];
array[index1] = array[index2];
array[index2] = aux;
}
// quickSort function begins here
ArrayList.prototype.quickSort = function() {
quick(this.array, 0, this.array.length - 1);
}
quick = function(array, left, right) {
var index;
if (array.length > 1) {
index = partition(array, left, right);
if (left < index - 1) {
quick(array, left, index - 1);
}
if (index < right) {
quick(array, index, right);
}
}
};
partition = function(array, left, right) {
var pivot = array[Math.floor((right left) / 2)],
i = left,
j = right;
while (i <= j) {
while (array[i] < pivot) {
i ;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
swap(array, i, j);
i ;
j--;
}
}
return i;
};
// Execute code block here
var array2 = new createNonSortedRandomArray(33);
console.log(array2.toString());
array2.quickSort();
console.log(array2.toString());
uj5u.com熱心網友回復:
問題出在quickSort訪問 的方法中this.array,但ArrayList實體沒有具有該名稱的屬性。查看建構式(在頂部),屬性是items. 所以將方法更改為:
ArrayList.prototype.quickSort = function() {
quick(this.items, 0, this.items.length - 1);
// ^^^^^ ^^^^^
}
這將解決問題。
備注:始終使用var、let或宣告變數const。對于使用函式運算式定義的幾個函式,您沒有這樣做swap:quick和partition. 在嚴格模式下,如果沒有該關鍵字,它甚至都不會決議。
uj5u.com熱心網友回復:
對我來說,在 JS 中實作各種演算法或資料結構的一個重要靈感來源是trekhleb的javascript-algorithms存盤庫。
請參閱快速排序。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/417251.html
標籤:
上一篇:為什么Jenkins一次一個哈希函式中沒有溢位檢查?
下一篇:矩陣最大對角模式匹配
