js sorting learning

Bubble Sort

	Array.prototype.bubbleSort = function() {
		// console.log(this)
		for (let i = 0; i < this.length - 1; i++) {
			for(let j = 0;j<this.length -1 - i; j+=1){  //  -1 可以用j+1来获取   - i是为了缩小循环节省时间
				if(this[j] > this[j+1]){
					const temp = this[j]   // 存储j  
					this[j] = this[j+1]   // 切换 j 和 j+1元素的位置
					this[j+1] = temp;  // j+1 = j 
				}
			}
		}
	}
	const arr = [ 5,4,3,2,1]
	arr.bubbleSort()
	console.log(arr)

Two nested loops

Time complexity O (n^2)

 

Select sort

Selection and sorting ideas 

Find the smallest value in the array, select it and place it first.

Then find the second smallest value, select it and place it in the second place.

By analogy, perform N-1 rounds

Array.prototype.slectionSort = function() {
		for (let i = 0; i < this.length - 1; i++) {
			let indexMin = i //  等于i  是为了缩减循环,因为找的是最小的值 每一轮都是最小的
			for(let j = i;j<this.length; j+=1){  // 等于i  是为了缩减循环, 这个循环是为了找到最小值的下标
			    if(this[j] < this[indexMin]){
					indexMin = j
				}
			}
			if( indexMin !== i){ //优化 避免最小值的下标和当前下标相等 
				const temp = this[i];  // 进行替换
				this[i] = this[indexMin]
				this[indexMin] = temp
			}
		}
	}
	const arr = [ 5,4,3,2,1]
	arr.slectionSort()
	console.log(arr)

Two nested loops

Time complexity O (n^2)

 

Insertion sort

The idea of ​​insertion sort

Start from the second number and go forward.

Behind his uncle.

And so on to the last number.

Array.prototype.insertionSotr = function() {
		for(let i =1 ; i < this.length; i+=1){  // 拿数组的第二个元素和前一个对比 所以i =1
		    const temp = this[i] // 获取当前对比元素
			let j = i; // 元素下标
			while (j>0){
				if(this[j-1] > temp){ // j-1 获取前一个元素的值 进行对比
					this[j] = this[j-1] ; // 进行替换 
				}
				else{
					break; // 终止循环
				}
				j -= 1; //循环条件
			}
			this[j] = temp ;  //进行插入
		}
		
	}
	const arr = [ 5,4,3,2,1,6,9,8,7]
	arr.insertionSotr()
	console.log(arr)

Two nested loops

Time complexity O (n^2)

 

Merge sort

The idea of ​​merging and sorting

Divide: Divide the array in half, and "divide" the sub-array recursively until it is divided into individual numbers.

Combine: Combine two numbers into an ordered array, and combine the ordered arrays until all sub-arrays are combined into a complete array

 

Combine two ordered arrays

Create an empty array res to store the final sorted array. ,

Compare the heads of two ordered arrays, and the smaller one is matched and pushed into res.

If the two arrays still have values, repeat the second step.

Array.prototype.mergeSort = function() {
		const rec =(arr) =>{ 
		    if(arr.length === 1) {return arr} // 预防死循环 并返回数组
			const mid = Math.floor(arr.length / 2) // 获取中间下标
			const left = arr.slice(0,mid) // 获取左边数组
			const right = arr.slice(mid,arr.length);// 右边的数组
			const orderLeft = rec(left) // 分隔左数组 得到有序数组 
			const orderRight = rec(right) // 分隔右数组 得到有序数组 
			const res = [];
			while(orderLeft.length || orderRight.length){
				if(orderLeft.length && orderRight.length){
					// 如果左边的对头 小于 右边对头 那么左边的出对 否则 右边出对  然后进入res 
					res.push(orderLeft[0] < orderRight[0] ? orderLeft.shift() : orderRight.shift())
				}else if(orderLeft.length){ // 如果左边还有值
					res.push(orderLeft.shift()) //那么不断的出对并进入数组
				}else if(orderRight.length){ // 如果右边还有值
					res.push(orderRight.shift()) //那么不断的出对并进入数组
				}
			}
			return res
		}
		const res = rec(this)
		res.forEach((n,i)=>{this[i] = n})
	}
	const arr = [ 5,4,3,2,1,6,9,8,7]
	arr.mergeSort()
	console.log(arr)

The time complexity of minutes is O(logN)

The combined time complexity is O(n)

Time complexity O(n* logN)

\

Quick sort

Partition: Choose a "benchmark" from the array arbitrarily, all elements smaller than the benchmark are placed in front of the benchmark, and elements that are smaller than the benchmark are placed behind the benchmark.

Recursion: Recursively partition the sub-arrays before and after the benchmark

 

Array.prototype.quickSort = function() {
		const rec =(arr) =>{
			if(arr.length === 1){return arr}
			// 分别存放 前后的数组
		   const left = []
		   const right = []
		   // 设置一个基准
		   const mid = arr[0]
		   //进行分区
		   for(let i =1; i<arr.length; i+=1){
			   if(arr[i] < mid){
				   left.push(arr[i])
			   }else{
				   right.push(arr[i])
			   }
		   }
		   
		   return [...rec(left),mid,...rec(right)] //...用于取出参数对象中的所有可遍历属性,拷贝到当前对象之中
		}
		const res = rec(this)
		res.forEach((n,i)=>{this[i] = n})
	}
	const arr = [ 5,4,3,2,1,6,9,8,7]
	arr.quickSort()
	console.log(arr)

The time complexity of recursion is O(logN)
The time complexity of partition operation is O(n)

Time complexity O(n*logN)

Sequential search    

Traverse the array.

Find an element equal to the target, and return its subscript.

After the traversal, if the target value is not found, it returns -1 

Array.prototype.sequentialSearch = function(val){
     for(let i=0;i<this.length;i+=1){
        if(this[i] === item){
            return i
        }
     }
     return -1

}
const res = [1,2,3,4,5,6].sequentialSearch(2)

Time complexity O(n)

 

Binary search

Starting from the middle element of the array, if the middle element happens to be the target value, the search ends.

If the target value is larger or smaller than the middle element, search in the half of the array that is larger or smaller than the middle element.

 

Array.prototype.binarySearch = function(val) {
		// * 二分搜索的数组是有序的 
		let low = 0;
		let high = this.length -1;
		while( low <= high){
			const mid = Math.floor((low+high) / 2)
			const elemnt = this[mid]
			if(elemnt < val){
				low = mid + 1
			}
			else if(elemnt > val){
				high = mid - 1
			}else {
				return mid
			}
		}
		return -1
	}
	const arr = [1,2,3,4,5].binarySearch(2)
	console.log(arr)

Time complexity O (logN)

 

 

 

 

 

 

 

 

 

 

 

Guess you like

Origin blog.csdn.net/wanghongpu9305/article/details/111461810