ホームページ > ウェブフロントエンド > jsチュートリアル > 初心者向けに JavaScript を使用した並べ替えアルゴリズムのハイライトを要約する

初心者向けに JavaScript を使用した並べ替えアルゴリズムのハイライトを要約する

Patricia Arquette
リリース: 2024-10-06 06:18:31
オリジナル
531 人が閲覧しました

Recap the highlight of the sorting algorithms using JavaScript for beginners

Sorting algorithms are methods used to arrange elements of a list or array in a specific order, typically numerical or lexicographical. They are fundamental in computer science for organizing data efficiently. It is an exercise in understanding how to break down a problem into steps and then implement those steps, i.e., how to create an algorithm. It's also an exercise in realizing that there are multiple methods to tackle an issue, and some are superior to others.

Why should I learn it?

  • It's a simple practical example for thinking recursively (see: merge sort and quick sort) and divide and conquer.
  • It's a simple but nontrivial example for algorithmic analysis (I.e. big O).
  • It's a traditional intro computer science topic that is expected to be taught.
  • It's a simple example to motivate why you might care about having a better algorithm than the simplest native one (I.e. bubble sort).

Here are some common sorting algorithms

Bubble Sort

Description: Repeatedly swaps adjacent elements if they are in the wrong order.
Time Complexity: O(n²)
Use Case: Simple but inefficient for large datasets.
Bubble Sort GitHub Gist


<p>var arr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37];</p>

<p>function bubbleSort(arr)<br>
{<br>
    var temp, i, j;</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext">for(i = 0; i&lt;arr.length; i++)
{
    for(j = 0; j&lt; arr.length; j++)
    {
        if (arr[j] &gt; arr[j+1])
        {
            temp = arr[j];
            arr[j] = arr[j+1];
            arr[j+1] = temp;
        }
    }
}

return arr;
ログイン後にコピー

}

console.log(bubbleSort(arr));

Enter fullscreen mode Exit fullscreen mode




Selection Sort

Description: Selects the smallest element from the unsorted part and swaps it with the first unsorted element.
Time Complexity: O(n²)
Use Case: Inefficient for large datasets but easy to implement.
Selection Sort GitHub Gist


<p>var arr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37];</p>

<p>function selectionSort(arr)<br>
{<br>
   var min;<br>
   for(var i = 0; i < arr.length; i++)<br>
   {<br>
       min = i;<br>
       for(var j = i+1; j < arr.length; j++ )<br>
       {<br>
           if (arr[j] < arr[min])<br>
           {<br>
               min = j;<br>
           }<br>
       }</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext">   if (min !== i) {
       var s = arr[min];
       arr[min] = arr[i];
       arr[i] = s;
   }
ログイン後にコピー

}

return arr;
}

console.log(selectionSort(arr));

Enter fullscreen mode Exit fullscreen mode




Insertion Sort

Description: Builds the sorted list one element at a time by inserting each element into its correct position.
Time Complexity: O(n²)
Use Case: Good for small datasets or nearly sorted arrays.
Insertion Sort GitHub Gist


<p>var arr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37];</p>

<p>function insertionSort(arr)<br>
{<br>
    for(let i = 1; i< arr.length; i++)<br>
    {<br>
        let key= arr[i];<br>
        let j = i - 1</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext">    while (j &gt;= 0 &amp;&amp; key &lt; arr[j]) {
        arr[j+1] = arr[j];
        j--;
    }
    arr[j+1] = key;
}

return arr;
ログイン後にコピー

}

console.log(insertionSort(arr));

Enter fullscreen mode Exit fullscreen mode




Merge Sort

Description: Divides the array into halves, recursively sorts them, and then merges the sorted halves.
Time Complexity: O(n log n)
Use Case: Efficient for large datasets, uses additional space for merging.
Merge Sort GitHub Gist
Merge Sort 2 GitHub Gist


<p>var unsortedArr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37];</p>

<p>function merge(left, right)<br>
{<br>
    const result = new Array();</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext">let i = j = 0;
while (i &lt; left.length &amp;&amp; j &lt; right.length) {
    if (left[i] &lt; right[j]){
        result.push(left[i]);
        i++;
    }else {
        result.push(right[j]);
        j++;
    }
}

while (i &lt; left.length) {
    result.push(left[i]);
    i++;
}

while (j &lt; right.length) {
    result.push(right[j]);
    j++;
}

return result;
ログイン後にコピー

}

function mergeSort(arr)
{
if (arr.length <= 1)
return arr;

const mid = Math.floor(arr.length/2);
const LA = new Array();
const RA = new Array();

for(let i = 0; i&lt; mid; i++)
    LA.push(arr[i]);

for(let j = mid; j&lt; arr.length; j++)
    RA.push(arr[j]);


const leftSorted = mergeSort(LA);
const rightSorted = mergeSort(RA);

return merge(leftSorted, rightSorted);
ログイン後にコピー

}

console.log(mergeSort(unsortedArr));

Enter fullscreen mode Exit fullscreen mode




Quick Sort

Description: Selects a pivot element and partitions the array into two sub-arrays: elements less than the pivot and elements greater than the pivot, then recursively sorts the sub-arrays.
Time Complexity: O(n log n) on average, O(n²) in the worst case.
Use Case: Fast and widely used for large datasets.
Quick Sort GitHub Gist


<p>var arr = [10, 55, 20, 4, 28, 69, 22, 85, 7, 37];</p>

<p>function partition(arr, low, high)<br>
{<br>
    const pivot = arr[high];</p>
<div class="highlight js-code-highlight">
<pre class="highlight plaintext">let i = low -1;

for(let j = low; j &lt;= high -1; j++)
{
    if (arr[j] &lt; pivot) {
        i++
        swap(arr, i, j)
    }
}

swap(arr, i+ 1, high);

return i + 1
ログイン後にコピー

}

function swap(arr, i, j)
{
let temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}

function QuickSort(arr, low, high)
{
if (low < high){
const po = partition(arr, low, high);
QuickSort(arr, low, po - 1);
QuickSort(arr, po + 1, high);
}

return arr;
ログイン後にコピー

}

console.log(QuickSort(arr, 0, arr.length - 1));

Enter fullscreen mode Exit fullscreen mode




Heap Sort

Description: Converts the array into a heap data structure and repeatedly extracts the maximum element to build the sorted array.
Time Complexity: O(n log n)
Use Case: Efficient and doesn't require extra space like merge sort.

Radix Sort

Description: Non-comparative sorting algorithm that sorts elements digit by digit, starting from the least significant digit to the most significant.
Time Complexity: O(nk) where k is the number of digits.
Use Case: Suitable for sorting numbers or strings with fixed-length keys.

Bucket Sort

Description: Divides elements into several buckets and then sorts each bucket individually (usually using another sorting algorithm).
Time Complexity: O(n + k) where k is the number of buckets.
Use Case: Effective when input is uniformly distributed over a range.

Each algorithm has its strengths and weaknesses, and the choice of which one to use depends on the size of the dataset, memory constraints, and whether the data is partially sorted.

Let's discuss how often we should practice those.

以上が初心者向けに JavaScript を使用した並べ替えアルゴリズムのハイライトを要約するの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
前の記事:HTML5 でのドラッグ アンド ドロップ 次の記事:JavaScript のディープコピーを理解する
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
最新の問題
関連トピック
詳細>
人気のおすすめ
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート