Javascript sort () bubble sort, selection sort, quick sort

Sort (), the array is positive sequence or in reverse order, to change the original array

var arr=[1,4,6,2,3,8,7,6,5,3,9,10];
arr.sort();
console.log(arr);//[1,10,2,3,3,4,5,6,6,7,8,9,12]

Do array in ascending or descending order, it is necessary to sort () in passing parameters

var arr=[1,4,6,2,3,8,7,6,5,3,9,10];
//return a-b,表示从小到大排列
//return b-a,表示从大到小排列
arr.sort(function(a,b){
    return a-b;
})
//return Math.random()-0.5; 表示乱序排列
arr.sort(function(){
	return Math.random()-0.5;
})
Bubble Sort
  1. Cycle from back to front
  2. Front to back inside the outer loop variable
  3. Determining whether the value is greater than the previous value, the previous value if the size of the value, then the switch position
function sort(arr){
	var len=arr.length;
	while(len>0){
	    for(var i=0;i<len;i++){
	        if(arr[i]>arr[i+1]){
	            var temp=arr[i];
	            arr[i]=arr[i+1];
	            arr[i+1]=temp;
	        }
	    }
	    len--;
	}
}
Selection Sort

First find the minimum or maximum value of the index, and then swap with the current target element at the smallest element to this

  1. Iterate
  2. Setting a minimum value for the current index value of the index
  3. The next item from the current traversing the end of the array
  4. All traversing judge the value of the smallest index value worth
  5. Switching element current value and the minimum value of the index
function sort(arr){
	var minIndex;
	for(var i=0;i<arr.length;i++){
		//假设第一位元素为最小值
	    minIndex=i;
	    for(var j=i+1;j<arr.length;j++){
	    	//判断如果当前元素大于最小值,则minIndex不变,否则把当前元素的下标赋值给变量minIndex
	        minIndex=arr[minIndex]<arr[j] ? minIndex : j;
	    }
	    //交换当前值和minIndex的元素
	    var temp=arr[i];
	    arr[i]=arr[minIndex];
	    arr[minIndex]=temp;
	}
}
Quick sort (fast discharge)
  1. Delete the middle of the array element, and this element will return to a variable
  2. Create two empty array, one left, one right, traverse the array, it will be less than the intermediate data elements into left, middle data element is greater than the stored right
  3. The array recursive left and right of the intermediate element array recursive return merged result
  4. At the top of the most function, you must write array length than 1, return the array
var arr = [1,4,2,2,3,10];
function sort(arr){
	//如果数组的长度小于等于1,则停止回调
    if(arr.length<=1) return arr;
    var left=[];
    var right=[];
    //取到数组最中间的值赋值给item,如果数组的长度为单数,则取中间前一位数
    var item=arr.splice(parseInt(arr.length/2),1)[0];
    for(var i=0;i<arr.length;i++){
    	//遍历数组,如果值小于item,则放入left数组中
        if(arr[i]<item) left.push(arr[i]);
        //如果值大小item,则放入right数组中
        else right.push(arr[i]);
    }
    arr=sort3(left).concat(item,sort3(right));
    return arr;
}
console.log(sort(arr));
Published 46 original articles · won praise 26 · views 10000 +

Guess you like

Origin blog.csdn.net/Charissa2017/article/details/103788008