JavaScriptのクイックソートを使用したリテラルの配列のソート
数値の配列を受け取り、クイックソートアルゴリズムを使用してソートするJavaScript関数を作成する必要があります。
クイックソート:
このアルゴリズムは基本的に分割統治アルゴリズムであり、ループのすべてのパスでピボットを選択し、ピボットよりも小さい要素をすべて左に配置し、ピボットよりも大きいすべての要素を右に配置します(昇順が反対の場合)
例
このためのコードは-
になりますconst arr = [43, 3, 34, 34, 23, 232, 3434, 4, 23, 2, 54, 6, 54];
// Find a "pivot" element in the array to compare all other
// elements against and then shift elements before or after
// pivot depending on their values
const quickSort = (arr, left = 0, right = arr.length - 1) => {
let len = arr.length, index;
if(len > 1) {
index = partition(arr, left, right)
if(left < index - 1) {
quickSort(arr, left, index - 1)
}
if(index < right) {
quickSort(arr, index, right)
}
}
return arr
}
const partition = (arr, left, right) => {
let middle = Math.floor((right + left) / 2),
pivot = arr[middle],
i = left, // Start pointer at the first item in the
array
j = right // Start pointer at the last item in the
array
while(i <= j) {
// Move left pointer to the right until the value at the
// left is greater than the pivot value
while(arr[i] < pivot) {
i++
}
// Move right pointer to the left until the value at the
// right is less than the pivot value
while(arr[j] > pivot) {
j--
}
// If the left pointer is less than or equal to the
// right pointer, then swap values
if(i <= j) {
[arr[i], arr[j]] = [arr[j], arr[i]] // ES6 destructuring swap
i++
j--
}
}
return i
}
console.log(quickSort(arr)); 出力
コンソールの出力-
[ 2, 3, 4, 6, 23, 23, 34, 34, 43, 54, 54, 232, 3434 ]
-
JavaScriptのArray.prototype.sort()。
JavaScript Array.prototype.sort()メソッドは、配列の並べ替えに使用されます。並べ替えの順序は、アルファベット、数字、昇順、降順のいずれかです。 以下は、Array.prototype.sort()メソッドのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-
-
JavaScriptオブジェクトの配列で配列のメソッドを使用していますか?
以下は、JavaScriptオブジェクトの配列で配列のメソッドを使用するためのコードです- 例 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <styl