Worst case time complexity of n- 2 , the average nlogn
Explanation: traversing a O (n), fast row using divide and conquer to traverse, as a binary tree, the number of times it traversed a relationship with his depth, n nodes, then the depth is at least log (n + 1), so the average nlogn; N binary tree that is the maximum depth, so the worst case time complexity of n- 2 .
// Get a reference number, and into the middle // this function is performed once, a reference number to find the correct position and to put int mid_index (ARR [], left, right) { int I = left + . 1 ; int J = right; int TEMP = ARR [I]; the while (I <= J) { the while (ARR [I] <TEMP) I ++ ; the while (ARR [J]> TEMP) J, ; IF (I < J) the swap (ARR [I], ARR [J]); } // to the borders of the swap (ARR [J], ARR [left]); return J; } void quick_sort (ARR [], left, right) { // ensure length of at least 2 if(left>=right) return; int mid=mid_index(arr,left,right); quick_sort(arr,left,mid-1); quick_sort(arr,mid+1,right); }
Boundary Analysis (first while loop condition i <= j):
When i = j, the right arr center, this time arr [i] == arr [j]:
- If the value is less than the temp, i ++ i to the first number is greater than temp, j of the same exchange was arr [j], and values arr [left] j are to the left than the reference value, the reference value is greater than the right , that the reference value to the correct location of the
- If arr [i] == arr [j]> temp, i is not judged, J, after the last number than the reference value, when i> j, exchange arr [j] and arr [left], supra
<iframe src="https://tool.lu/coderunner/embed/721.html" width="650" height="550" frameborder="0" mozallowfullscreen webkitallowfullscreen allowfullscreen></iframe>