Interview questions---What is the space complexity of quick sort? What is the best and worst case of time complexity, and what are the optimization solutions?

 

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)

What is the space complexity of quicksort?

The main reason is the use of stack space caused by recursion. In the best case, the depth of the recursion tree is log2​n

The space complexity is O(logn)

Worst case ,

Need to make n-1 recursive calls, and its space complexity is O(n),

Average,

The space complexity is also O(logn).

What is the best and worst case of time complexity, and what are the optimization solutions?

Under optimal conditions

The time complexity of the quick sort algorithm is O(nlogn).

Worst case ,

The sequence to be sorted is in positive or reverse order. Each division only gets a sub-sequence with one less record than the previous division. Note that the other is empty. If the recursive tree is drawn, it is an oblique tree .

At this time, n-1 recursive calls need to be performed, and the i-th division requires n-i keyword comparisons to find the i-th record, which is the position of the pivot, so the number of comparisons is

img

Finally, its time complexity is O(n^2).

Time complexity optimization:
using the method of taking the three out can effectively reduce the time complexity in the worst case.
The meaning of the three is to set the pivot value to the middle value of A[low], A[(low + high)/2], and A[high].

 

 

 

======================== 

Just sort out the unsure answer right

 

 

 

Guess you like

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