js several of the most common sorting algorithms

js sorting algorithm:

First customize an array which contains several numbers to pass parameters for subsequent calls to various sorting functions

//自定义三个数字5 10 20 进行降幂排序
var a=[5,10,20,50,23];

1.sort() sort

Only characters can be sorted. If you want to sort numbers, you need to use the "comparison function (here is sortby(), no specified name, name it yourself)".
Sort from small to large to ab, from large to small to ba

function sortby(a,b){
    
    
	return b-a;
}		
document.write(a.sort(sortby));

2. Choose a sort

Each cycle finds the largest element, and then exchanges it with the last one sorted before

//降序
function selectSort(a){
    
    
	var min=null
	for(var i=0;i<a.length-1;i++){
    
    
		min=i;
		for(var j=i+1;j<a.length;j++){
    
    
			if(a[j]>a[min]){
    
    
				min=j;
			}
			if(min!=i){
    
    
				var c=a[min];
				a[min]=a[j];
				a[j]=c;
			}
		}
	}
	return a;
}
document.write(selectSort(a))

3. Bubble sort

Compare two adjacent elements, put the smaller one behind

function bubbleSort(a){
    
    
	for(var i=0;i<a.length-1;i++){
    
    
		for(var j=0;j<a.length-i-1;j++){
    
    
			if(a[j]<a[j+1]){
    
    
				var c=a[j];
				a[j]=a[j+1];
				a[j+1]=c;
			}
		}
	}
	return a;
}	
document.write(bubbleSort(a));

4. Insertion sort

Starting from the number with subscript 1 in the array, compare with the previous element, and put the smaller one in the back

function insertSort(a) {
    
    
    for (var i = 1; i <a.length; i++) {
    
    
       // 待插元素
       var item = a[i];
       //排序后的末尾元素
       var j = i - 1;
       // 从排序好的末尾元素开始遍历
       // 如果大于待插元素就把当前元素往后挪
       while (j >= 0 && a[j] > item) {
    
    
           arr[j + 1] = a[j];
           j--;
       }
       // 插入待插元素
       a[j + 1] = item;
   }
   return arr;
}
document.write(insertSort(a));

5. Quick sort

function quickSort(a){
    
    
	if(a.length<=1){
    
    
		return arr
	}
	var midindex=Math.floor(arr.length/2)
	var miditem=a.splice(midindex,1)[0]
	var left=[]
	var right=[]
	for(var i=0;i<a.length;i++){
    
    
		if(miditem>a[i]){
    
    
			left.push(a[i])
		}else{
    
    
			right.push(a[i])
		}
	}
	return quickSort(left).concat(miditem,quickSort(right))
}

document.write(quickSort(a));

Guess you like

Origin blog.csdn.net/isfor_you/article/details/109514314