JavaScript Classic Algorithm Learning 1: auxiliary class for generating random arrays

Source: Internet
Author: User

Auxiliary classes

In several classical sorting algorithm learning section, for the convenience of unified testing of different algorithms, a new auxiliary class, the main function is: to produce a specified length of the random array, provide a printout array, exchange two elements and other functions, the code is as follows:

functionarraysortutility (numofelements) { This. Dataarr = [];  This. pos = 0;  This. numofelements =numofelements;  This. Insert =Insert;  This. toString =toString;  This. Clear =Clear;  This. SetData =SetData;  This. Swap =swap;  for(vari = 0; i < numofelements.length; i++) {         This. dataarr[i] =i; }}arraysortutility.prototype={constructor:arraysortutility, Bubblesort:bubblesort,//Add a new method below}

Several important methods are implemented as follows:

function SetData () {    for (var-numofelements; i++) {        this  . Dataarr[i] = Math.floor (Math.random () * (this. numofelements + 1));}    }

Several other functions are implemented as follows:

functionClear () { for(vari = 0; I < This. dataarr.length; i++) {         This. dataarr[i] = 0; }}functionInsert (Element) { This. dataarr[ This. pos++] =element;}functiontoString () {varRestr = "";  for(vari = 0; I < This. dataarr.length; i++) {Restr+= This. Dataarr[i] + ""; if(i > 0 & i% 10 = = 0) {Restr+ = "\ n"; }    }    returnrestr;}functionswap (arr, index1, index2) {vartemp =ARR[INDEX1]; ARR[INDEX1]=Arr[index2]; ARR[INDEX2]=temp;}

JavaScript Classic Algorithm Learning 1: auxiliary class for generating random arrays

Related Article

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.