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