Why insert is sorted faster than quick sort by sorted array

I compare insert sorting with quick sort. I found out why qsort is slower on an almost sorted array, but I can’t understand why sorting sorting is much faster, and of course, it still has to compare almost as many elements in the array?

+3
source share
4 answers

The reason that insertion sorting is faster on sorted or almost sorted arrays is because when inserting elements into the sorted part of the array, it hardly needs to move any elements at all. For example, if the sorted part of the array 1 2, and the next element - 3, then only one comparison - 2 < 3- to determine that it does not need to be moved 3at all. As a result, sorting an insert by an already sorted array is linear-temporal, since only one comparison is needed per element.

+3
source

. , . (LinkedList ArrayList). , , - . , , LinkedList, .

+1

Quicksort ( O (n ^ 2)) (. quicksort ).

, - ( O (n)), quicksort .

0

- (O (n)) (O (n ^ 2)).

, , .

So, when you see the algorithm, you find that in insertion sorting you have only comparison n, since when we insert an element, we compare only with the left element and its completion. On the other hand, in the case of quick sorting u, you must continue to compare your rotation element with your entire left element and reduce its array by a constant one factor, resulting in approximately n ^ 2 comparison.

-1
source

All Articles