JS: Data structure note 11--sorting algorithm (1)

Source: Internet
Author: User

Basic Preparation:

  function  CArray (numelems) {  this.datastore = [];  This.pos = 0;  This.numelems = Numelems;  This.insert = insert;  this.tostring = toString;  This.clear = clear;  This.setdata = SetData;  This.swap =swap;  for (var i = 0; i < Numelems; ++i) {  this.datastore[i] = i;  }  }  function  SetData () {for  (var i = 0; i < This.numelems; ++i) {  This.datastore[i] = Math.floor (math.rando M () * +);//0-99  }  }  function Clear () {for  (var i = 0; i <  this.numelems; ++i) {  THIS.D Atastore[i] = 0;  }  }  function Insert (elem) {  this.datastore[this.pos++] = elem;  }  function toString () {  var str = "";  for (var i = 0; i < this.dataStore.length; ++i) {  str + = This.datastore[i] + "";  if (i > 0 && (i+1)%10 = = = 0) {  str + = "\ n";  }  }  return str;  }  Function Swap (ARR,INDEX1,INDEX2) {  var temp = arr[index1];  ARR[INDEX1] = Arr[index2];  ARR[INDEX2] = temp;  }

Basic Sorting algorithm:

    • Bubble sort: One of the easiest and slowest algorithms to implement
      • The next two elements are compared and sorted from the beginning to the last, at which point the last one is determined to be the largest;
      • Repeat the above steps but not compare what has been determined, at this time to determine the last second is the second largest;
      • Continue repeating until the first element is left, and make sure it is the smallest;

Effect:

  function Bubblesort () {    var numelems = this.dataStore.length;    var temp;    for (var outer = numelems; outer > 1,--outer) {for      (var inner = 0; inner < outer; ++inner) {        if (this.datast Ore[inner] > This.datastore[inner + 1]) {          swap (This.datastore,inner,inner + 1);}}}  

Demo

    • Select Sort:

JS: Data structure note 11--sorting algorithm (1)

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.