Home > Web Front-end > JS Tutorial > body text

Summary of sorting methods implemented in JS

php中世界最好的语言
Release: 2018-04-18 15:37:28
Original
1380 people have browsed it

This time I will bring you a summary of JS implementation of sorting methods. What are the precautions for JS implementation of sorting? . The following is a practical case, let's take a look.

Bubble sort

 function Bubble(arr){
    var temp; for(var i=0;i<arr.length-1;i++){
      for(var j=i+1;j<arr.length;j++){
        if(arr[i]>arr[j]){
          temp=arr[i];
          arr[i]=arr[j];
          arr[j]=temp;
        }
      }
    }
    return arr;
  }
  console.log(Bubble([2,5,1,0,6,2]))  //[0,1,2,2,5,6]
Copy after login

Select sort

function selctor(arr){
    var min;
    for(var i=0;i<arr.length-1;i++){
      min=i;
      //依次找到为最小值的索引
      for(var j=i+1;j<arr.length;j++){
        if(arr[min]>arr[j]){
          min=j;
        }
      }
      //如果最小值不在当前位置上 就交换到位置i
      if(min!=i){
        swap(arr,min,i)
      }
    }
    return arr
  }
  function swap(arr,index1,index2) {
    var temp=arr[index1];
    arr[index1]=arr[index2];
    arr[index2]=temp;
  }
Copy after login

Insertion sort

 function insert(arr){
    var j,key;
   for(var i=1;i<arr.length;i++){
     j=i;
     key=arr[i];
     while(--j>-1){
       if(arr[j]>key) {
         arr[j + 1] = arr[j];
       }else{
         break;
       }
     }
     arr[j+1]=key;
   }
   return arr
  }
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

Detailed explanation of using vuex Actions

##Detailed explanation of jQuery implementation of timer function

The above is the detailed content of Summary of sorting methods implemented in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!