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
JS: Data structure note 11--sorting algorithm (1)