Sorting array, deduplication, scrambled

Bubble Sort

It repeatedly visited elements of the column to sort, in order to compare two adjacent elements, if the order (such as descending, the first letter from Z to A) put the wrong they exchanged over. Working visit element is repeated until there is no need to swap adjacent elements, that is to say the element column has been sorted completed

 

 

 

 

 

 

Bubble Sort:

function bubbleSort(arr){
var len=arr.length,j;
var temp;
while(len>1){
for(j=0;j<len-1;j++){
if(arr[j]>arr[j+1]){
temp=arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
}
}
len--;
}
return arr;
}
var arr = [3, 2, 4, 9, 1, 5, 7, 6, 8];
var arrSorted = bubbleSort(arr);
console.log(arrSorted);
alert(arrSorted);

 

Deduplication:

1, give an array sort


unique4 function (ARR) {
// sort to ARR
arr.sort (function (A, B) {return ab &})
// iterate
for (var. 1 = I; I <arr.length; I ++) {
// if the current value is equal to the preceding value of the
IF (ARR [I] === ARR [-I. 1]) {
// delete the value
arr.splice (I,. 1);
// deleted as a value, to the need to cycle before moving a
i--;
}
}
return ARR;
}

 


2, by the subscript


unique5 function (arr) {
// iterate
for (var I = 0; I <arr.length; I ++) {
// iterate to find arr current equal to the value
for (var j = i + 1 ;;) {
// record found subscript j
j = arr.indexOf (ARR [I], j);
// if j is -1, the same value as representing no behind the
IF (j == -1) {
BREAK;
}
// delete the value
arr.splice (J,. 1);
}
}
return ARR;
}

 

 

3, ES6 new syntax:


unique6 function (ARR) {
// new syntax for ES6
return the Set new new (ARR);
}
var ARR = [5,4,9,1,6,8,7,5,4,2,4,5,6,4 , 2,6,4,2,1,5,9]

 

 

Out of order:

 

Guess you like

Origin www.cnblogs.com/w-yue/p/11770404.html