js implements basic sorting - bubble sort, selection sort, insertion sort

1. Bubble sort:

function bubbleSort(arr) {
	var len=arr.length;
	for(var outer=0;outer<len-1;outer++)
	   for (var inner = 0; inner <len-outer + 1; inner ++) {
		if(arr[inner]>arr[inner+1]){ //Compare adjacent elements
			let temp=arr[inner+1];
			arr[inner+1]=arr[inner];
			arr[inner]=temp;
		}
	}

	return arr;
}

Second, the selection sort:

function selectionSort(arr) {
            var len=arr.length;
            var temp;
            for (var i = 0; i <len-1; i ++) {
                var strmin = i;                    
                for(var j=i+1;j<len;j++){
                    if(arr[j]<arr[strmin]){ //find the minimum value of the remaining elements
                        strmin = j;
                    }
                }

                temp=arr[i];
                arr [i] = arr [strmin];
                arr[strmin]=temp; // reset the minimum value

            }
            return arr;
       }

3. Insertion sort

The first pass sorts the elements at subscript 1 to ensure that the elements on the array [0,1] are ordered;

The second pass sorts the elements at subscript 2 to ensure that the elements on the array [0,2] are ordered;

.....

.....

The N-1th pass sorts the elements at subscript N-1 to ensure that the elements on the array [0, N-1] are ordered, that is, the entire array is ordered.

Its recursive idea is reflected in: when sorting the elements at position i, the elements at [0,i-1] must be already in order.

function insertSort(arr) {
            var len=arr.length;

            for (var i = 1; i <len; i ++) {
                temp=arr[i];
                // for (var j = i;j>=0; j--) {
                //     if(arr[i-1]>arr[i]){
                //         arr[i]=arr[i-1];
                //     }else{
                //         break;
                //     }
                // }
                var j = i;
                while(j>=0 && arr[j-1]>=temp){ //Find the appropriate position of the outer loop element
                    arr[j]=arr[j-1]; //Move the elements in the inner loop to the right
                    j--;
                }

                arr[j]=temp; //Classify the outer loop elements as
            }
            return arr;

       }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812490&siteId=291194637