首頁 > web前端 > js教程 > 為初學者回顧一下使用 JavaScript 的排序演算法的亮點

為初學者回顧一下使用 JavaScript 的排序演算法的亮點

Patricia Arquette
發布: 2024-10-06 06:18:31
原創
540 人瀏覽過

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中文網其他相關文章!

來源:dev.to
上一篇:HTML5 中的拖放 下一篇:了解 JavaScript 中的深拷貝
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
關於CSS心智圖的課件在哪? 課件
來自於 2024-04-16 10:10:18
0
0
2015
相關專題
更多>
熱門推薦
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板