Josefus.mv
Josefus.mv

Reputation: 117

Why my selection sort is slower than insertion sort

I'm trying to write the implementations for selection sort and insertion sort. And tested them with an auto generated array and evaluates the time consuming with Posix gettimeofday in u-second accuracy, under MAC OS.

But in most case, with an total 65525 and range from -65525 and +65525 input array, the insertion sort is far faster than selection sort, says about half of time.

implementation see below:

void selectionSort (vector<int>& ns) {
uint_t j, minInd; 
for (uint_t i = 0; i< ns.size() - 1; i++) {
    j = i + 1;         
    minInd = i;
    while (j < ns.size()) {
        if(ns[j] < ns[minInd])
           minInd = j; 
        j++;
    }
    if (minInd != i) {
        int tmp = ns[minInd];
        ns[minInd] = ns[i];
        ns[i] = tmp;
    }
    }
} 

insertSort (vector<int>& ns){
       for(int i = 1; i < (int)ns.size(); i++) {
       int key = ns[i]; 
       int j = i - 1;
       for( ; j >= 0; j--) {
           if (ns[j] > key ) {
               ns[j+1] = ns[j]; 
           } else {
               break;
           }
       }
       ns[j+1] = key;
    }
}

Some Test results:

Insert Sort:

Min=(-65524), index=(89660); Max=(62235), index=(23486) ShowSysTime millisecond: 1447749079447950, diff time to last record:20092583 Min=(-65524), index=(0); Max=(62235), index=(131050)

Selection Sort:

Min=(-65524), index=(89660); Max=(62235), index=(23486) ShowSysTime millisecond: 1447749114384115, diff time to last record:34934768 Min=(-65524), index=(0); Max=(62235), index=(131050)

The insertion sort is from book ITA, so I suspect my selection sort has something not correct.

Upvotes: 1

Views: 2687

Answers (2)

Ashish Ani
Ashish Ani

Reputation: 332

In all the cases of selection sort, a selected value is compared with all other not sorted values. Hence, time complexity is always quadratic or n^2.

Where as in Insertion Sort, in best case it was linear (as, the value to be inserted is always greater than value at last index of sorted part). It become quadratic in worst case.

Upvotes: 1

dr_
dr_

Reputation: 2292

Selection sort is a simple but inefficient sorting algorithm. It has always quadratic complexity, in the worst case as well as in the best case.

On the other hand, insertion sort is quadratic at worst but linear at best. Therefore it is expected that, in some cases, it will perform better than selection sort. It would be surprising the opposite.

Upvotes: 4

Related Questions