js to achieve array bubble sort quick sort principle
- 2021-01-25 07:05:15
- OfStack
In this paper, we share the js array bubble sort, quicksort implementation principle, for your reference, the specific content is as follows
1. Bubble Sort:
If you want to sort from the smallest to the largest, put the smallest bit in the front and the largest bit in the back. In simple words, you can exchange their positions repeatedly, and then you can get the sorting effect.
var arr = [3,1,4,2,5,21,6,15,63];
function sortA(arr){
for(var i=0;i<arr.length-1;i++){
for(var j=i+1;j<arr.length;j++){
// For the first 1 And after a value 1 A value comparison
var cur = arr[i];
if(cur>arr[j]){
// Because I'm swapping values, I'm going to put them back 1 We're going to have to save it
var index = arr[j];
// Exchange value
arr[j] = cur;
arr[i] = index;
}
}
}
return arr;
}
// because 1 Subcycles can only be swapped 1 Is the largest value, so it needs to be reset 1 layer for Cycle.
2. Quick sort:
You take one value from the middle of the array, and you compare each value to the other values in the array, and if you put a edge on something greater than that, you put a edge on something less than that, and you combine those, and you compare them, and so on and so on.
var arr = [3,1,4,2,5,21,6,15,63];
function sortA(arr){
// If only 1 Bit, there is no need to compare
if(arr.length<=1){
return arr;
}
// Gets the index of the intermediate value
var len = Math.floor(arr.length/2);
// Intercept the median
var cur = arr.splice(len,1);
// Less than the median and put it in here
var left = [];
// I'm going to put greater than that inside
var right = [];
for(var i=0;i<arr.length;i++){
// Determine whether it is greater than
if(cur>arr[i]){
left.push(arr[i]);
}else{
right.push(arr[i]);
}
}
// By recursion, up 1 Round the better array merge, and compare again.
return sortA(left).concat(cur,sortA(right));
}
To learn more about javascript sorting, see javascript sorting method implementation.
The above is all the content of this article, I hope to help you learn.