A common sort algorithm (instance) in JavaScript

Source: Internet
Author: User

Select sort

The code is as follows Copy Code


function Selectsort (array) {
var index, temp;

for (var i = 0; i < array.length-1; i++) {
index = i;
temp = Array[i];
for (var j = i + 1; j < Array.Length; J + +) {
if (temp > Array[j]) {
index = j;
temp = Array[j];
}
}
Array[index] = Array[i];
Array[i] = temp;
}
return array;
}

Test
var test = [2, 1, 22, 64, 4, 12, 56, 89, 7, 9, 85];
Console.log (Selectsort (test)); 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.20.21.22.


Bubble sort Www.111cn.net

The code is as follows Copy Code


Bubble sort
function Bubblesort (array) {
var temp;

for (var i = 0; i < array.length-1; i++) {
for (var j = 0; J < array.length-i-1; j +) {
if (Array[j] > array[j+1]) {
temp = Array[j];
ARRAY[J] = array[j+1];
ARRAY[J+1] = temp;
}
}
}
return array;
}

Test
var test = [1, 2, 22, 64, 4, 12, 56, 89, 7, 9, 85];
Console.log (test) (Bubblesort);


Insert Sort

  code is as follows copy code

function Insertsort (array) {
 var len = array.length;
 var temp;

 for (var i = 1; i < Len; i++) {
  temp = array[i];
  for (var j = i-1; J >= 0 && temp < ARRAY[J]; j--) {
   array[j+1] = array[j];
  }
  array[j+1] = temp;
 }
 return Array;
}

//test
var test = [1, 2, 4, 7, 9, Console.log];
Insertsort (test);//[1, 2, 4, 7, 9,,,,, 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.