Home >Web Front-end >JS Tutorial >js implements array bubble sorting and quick sorting principles_javascript skills
This article shares the implementation principles of js array bubble sort and quick sort for your reference. The specific content is as follows
1. Bubble sort :
Take any digit from the array and compare it with the next digit. If you want to sort from small to large, then put the small one in the front and the big one in the back. Simply put, swap them. position, and the sorting effect can be obtained by repeatedly exchanging positions.
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++){ //获取第一个值和后一个值比较 var cur = arr[i]; if(cur>arr[j]){ // 因为需要交换值,所以会把后一个值替换,我们要先保存下来 var index = arr[j]; // 交换值 arr[j] = cur; arr[i] = index; } } } return arr; } //因为一次循环只能交换一个最大的值,所以需要再套一层for循环。
2. Quick sort:
Take a value from the middle of the array, and then compare this value with the values in the array one by one. If it is greater, put it aside, if it is smaller, put it aside, then merge these, compare again, and repeat.
var arr = [3,1,4,2,5,21,6,15,63]; function sortA(arr){ // 如果只有一位,就没有必要比较 if(arr.length<=1){ return arr; } // 获取中间值的索引 var len = Math.floor(arr.length/2); // 截取中间值 var cur = arr.splice(len,1); // 小于中间值放这里面 var left = []; // 大于的放着里面 var right = []; for(var i=0;i<arr.length;i++){ // 判断是否大于 if(cur>arr[i]){ left.push(arr[i]); }else{ right.push(arr[i]); } } // 通过递归,上一轮比较好的数组合并,并且再次进行比较。 return sortA(left).concat(cur,sortA(right)); }
If you want to learn more about javascript sorting, please click "Javascript Sorting Method Implementation" .
The above is the entire content of this article, I hope it will be helpful to everyone’s study.