Home  >  Article  >  Web Front-end  >  Detailed explanation of selection sorting in JavaScript

Detailed explanation of selection sorting in JavaScript

韦小宝
韦小宝Original
2018-03-14 14:12:582651browse

This article talks about selection sorting in JavaScript. If you don’t know about selection sorting in JavaScript, then let’s take a look at this article together, using JavaScript Simple selection and sorting, let’s stop talking nonsense and get to the point!

Selection sort

One of the most stable sorting algorithms, because no matter what data is entered, the time complexity is O(n²) . . . So when using it, the smaller the data size, the better. The only advantage may be that it does not occupy additional memory space.

Select sorting animation demonstration

Detailed explanation of selection sorting in JavaScript

##JavaScript code implementation:

function selectionSort(arr) {  
   var len = arr.length;  
   var minIndex, temp;  
   for (var i = 0; i < len - 1; i++) {  
       minIndex = i;  
       for (var j = i + 1; j < len; j++) {  
           if (arr[j] < arr[minIndex]) {     //寻找最小的数  
               minIndex = j;                 //将最小数的索引保存  
           }  
       }  
       temp = arr[i];  
       arr[i] = arr[minIndex];  
       arr[minIndex] = temp;  
   }  
   return arr;}

The above is all the content of this article, if you haven’t If you know it well, you can easily master it if you can realize more of both sides by yourself!



Related recommendations:
Implementation of PHP selection sort

JS bubble sort selection sort Example analysis with insertion sort

The above is the detailed content of Detailed explanation of selection sorting in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn