Insertion sort or sort option?

I have a piece of code here . Tested it on several occasions, it seems to be working fine.

I wrote the code at a time to sort the insert after learning the algorithm, but I wonder if this is a traditional insert sort?

I have a feeling that this may be a variation (a modified version) of the choice, which is the cause of my confusion.

In particular, this is an area of ​​concern: (given array of aelements n)

for(i=1;i<n;i++){
    for(j=0;j<i;j++){
        if(a[i] < a[j]){
            temp = a[i];
            a[i] = a[j];
            a[j] = temp;
        }
    }      
} 

Also, are there more / less comparisons or swaps with this kind of approach?

Thanks in advance for your help.

+4
2

: , . , .

, , , . , , , , .

, , .

  • i a[i].
  • , , a[i]
  • ( , ), a[i] a[j], .
  • a[i] , ...
  • , (: ?) , a[i], . a[i] , , .

, . , - . "", , .

... - / ?

, . O (n), n. , O (N ^ 2) , . ; .


++

,

template<typename Iter>
void insertion_sort(Iter first, Iter last)
{
    for (Iter it = first; it != last; ++it)
        std::rotate(std::upper_bound(first, it, *it), it, std::next(it));
}

, ( ), ++, , : std::upper_bound std::rotate.

std::upper_bound . , , , (*it). - O (logN), , O (n).

, std::rotate , , . :

0 1 2 3 5 6 4
        ^ ^ *  these will be rotated right one element

0 1 2 3 5 6 
            4

0 1 2 3   5 6 
        4

0 1 2 3 4 5 6 

, .

, - , - . , , :

  • .
  • .

.

+3

. :

for(j=0;j<i;j++){
    if(a[i] < a[j]){
        temp = a[i];
        a[i] = a[j];
        a[j] = temp;
    }
} 

:

for(j = 0; j < i ; j++)
    if(a[i] < a[j])
        swap(a[i], a[j]);

, subarray a[0:i - 1] . n, a[i] [n, i - 1] :

while(j < i && a[j] <= a[i])
    j++;

//insert a[i] at the appropriate index
int tmp = a[j];
a[j] = a[i];

//push all elements starting from index n one index further
for(; j < i; j++){
    int swap = tmp;
    tmp = a[j];
    a[j] = swap;
}

: n ( a[i]) . a[i] a[n]. a[i] tmp - . i - 1, , i. .

for(i = 0; i < array_length; i++)
     insert a[i] at appropriate position
+3

Source: https://habr.com/ru/post/1667454/


All Articles