Code summary for JS sorting methods (sort bubble select insert)
- 2020-12-09 00:40:55
- OfStack
I recently started learning about data structures.
One by one, I hope I can stick to it.
Because the direction is front end, it is implemented with JavaScript.
//sort The sorting
var testArr1=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
var testArr2=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
var testArr3=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
testArr1.sort();// Sorting results: [15, 19, 2, 26, 27, 3, 36, 38, 4, 44, 46, 47, 48, 5, 50]
testArr2.sort(function(a,b){return a>b});// Sorting results: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
testArr3.sort(function(a,b){return a-b});// Sorting results: [2, 3, 4, 5, 15, 19, 26, 27, 36, 38, 44, 46, 47, 48, 50]
/ / Bubble sorting
var testArr1=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
var testArr2=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
function bubbleSort1(array){
for(i=array.length-1;i>0;i--){
for(j=0;j<i;j++){
if(array[j+1]<array[j]){
var temp=array[j+1];
array[j+1]=array[j];
array[j]=temp;
}
}
}
}
function bubbleSort2(array){
for(i=array.length-1;i>0;i--){
for(j=0;j<i;j++){
if((array[j+1]-array[j])<0){
var temp=array[j+1];
array[j+1]=array[j];
array[j]=temp;
}
}
}
}
bubbleSort1(testArr1);// Sorting results: [2,3,4,5,15,19,26,27,36,38,44,46,47,48,50]
bubbleSort2(testArr2);// Sorting results: [2,3,4,5,15,19,26,27,36,38,44,46,47,48,50]
/ / Select sorting
var testArr=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
function selectSort(array){
for(i=0;i<array.length;i++){
var slc=array[i];// Initially set the unsorted number 1 The value is selected
var slcIdx;// record 1 After the secondary loop as the selected value index
for(j=i;j<array.length;j++){
if(array[j]<slc){
slc=array[j];
slcIdx=j;
}
}
if(slc!=test[i]){// If it ends up as the value and the initial of the selected value slc Values are not equal
var temp=array[i];
array[i]=array[slcIdx];
array[slcIdx]=temp;
}
}
}
selectSort(testArr);// The ranking results are: [2,3,4,5,15,19,26,27,36,38,44,46,47,48,50]
/ / Insert sorting
var testArr=[3, 44, 38, 5, 47, 15, 36, 26, 27, 2, 46, 4, 19, 50, 48];
function insertSort(array){
for (var i = 0 ; i < array.length-1; i++) {// Pay attention to i Less than the length of the array -1 Otherwise, it will cause the array to cross the boundary and form an endless loop
var curElement=array[i+1];
for (var j = i; j >= 0; j--) {
if(curElement<array[j]){
array[j+1]=array[j];
if(j==0){// when j==0 , indicates that the array has been sorted to the very beginning
array[0]=curElement;
}
}else{
array[j+1]=curElement;
break;
}
};
};
}
insertSort(testArr);// And the ranking is :[2,3,4,5,15,19,26,27,36,38,44,46,47,48,50]