Demand:
An array of var arr = [4,7,2,9], sorted by the new array var newArr = [2,4,7,9] or [9,7,4,2]
What we're going to get is an array of the positions of each entry in the sorted array of elements in the new array: [2,4,7,9] corresponds to [1,2,0,3]/[9,7,4,2] [2,1,3,0]
Programme one:
1Array.prototype.getIndex =function () {2 varOrderlength = This. Length;3 vartemp, TP;4 varc = [];5 for(varL = 0; L < Orderlength; l++) {6C[L] =l;7 }8 for(varu = 0; U < orderlength; u++) {9 for(varv = 0; v < orderlength-u-1; v++){Ten if( This[V] > This[V+1]) { Onetemp = This[v]; A This[V] = This[V+1]; - This[V+1] =temp; -TP =C[v]; theC[V] = c[v+1]; -C[V+1] =TP; - } - } + } - returnC; + //return this; A } at vararr = [4,7,2,9]; -Console.log (Arr.getindex ());
Scenario Two:
1 varA = [4,7,2,9];2 varNEWARR = [];3 for(vari = 0, n = a.length; I < n; ++i) {4 Newarr.push ({5 Data:a[i],6 index:i7 })8 }9Newarr.sort (function(A, b) {Ten returnA.data-B.data; One }) A varindex = []; - for(vari = 0, n = newarr.length; I < n; ++i) { - Index.push (newarr[i].index); the } -Console.log (Newa);
I am stupid only think of these two solutions, for better solutions
Get the index algorithm implementation after array sorting