Sorting of arrays
var arr = [];
for (Var i=0;i<20;i++) {
Arr.push (Math.floor (Math.random () *100))
}
Generates an unordered array of arr
function sort (arr,start,end) {
Array length is 1
if (start = = end) {
return [Arr[start]]
}else if (start = = end-1) {
Array length is 2, sorted by numeric size
if (Arr[start]>arr[end]) {
return [Arr[end],arr[start]]
}else{
return [Arr[start],arr[end]]
}
}
Half the length of the array
var L = Math.floor ((start+end)/2);
Left array
var arrleft = sort (arr, start,l);
Right array
var arrright = sort (arr,l+1,end);
return results
var result = [];
Divided into two parts about two arrays only than the first number in the array, that value is small to put who in the results, and the small number of deleted, solid use the shift method in the array. Once the left or right array is present, there is no data
The result array is combined with an array of data and concat, and returns the result
while (arrleft.length>0 | | arrright.length>0) {
if (arrleft.length==0) {
result = Result.concat (arrright);
Break
}else if (arrright.length==0) {
result = Result.concat (arrleft);
Break
}
if (Arrleft[0]<arrright[0]) {
Result.push (Arrleft.shift ())
}else{
Result.push (Arrright.shift ());
}
}
return result;
}
var arrsort = sort (arr,0,arr.length-1);//parameter array, start position, end position
document.write (arr+ ' <br/> ' +arrsort);
Data de-weight
var arr = [];
for (Var i=0;i<20;i++) {
Arr.push (parseint (Math.random () *10));
}
Array.prototype.indexOf = function (n) {
for (Var i=0;i<this.length;i++) {
if (this[i] = = N) {
return i;
}
}
return-1;
}
function Removedup (arr,s,e) {
if (s==e) {
There's only one split.
return [Arr[s]]
}else if (s==e-1) {
To optimize the rest of the two, you don't have to split.
if (Arr[s]==arr[e]) {
return [Arr[s]]
}else{
return [Arr[s],arr[e]];
}
}
The array is divided into two segments,
var L = Math.floor ((s+e)/2);
Left
var ArrL = removedup (arr,s,l);
Right
var arrr = removedup (arr,l+1,e);
The result is to copy the left side first.
var result = ArrL;
Loops Insert non-repeating data into the result
for (Var i=0;i<arrr.length;i++) {
if (Result.indexof (arrr[i]) = =-1) result.push (Arrr[i])
}
return result; return results
}
var arrdup = removedup (arr, 0, arr.length-1);
document.write (arr+ ' <br/> ' +arrdup);
Transfer from http://www.jb51.net/article/42090.htm
JS array Quick Sort/de-weight