From charlesreid1

(Created page with "==Analysis of Selection Sort== Consider the following selection sort algorithm: <pre> selection_sort(int s[], int n) { int i, j; // counters int min; // index of min...")
 
Line 29: Line 29:


==Analysis of Insertion Sort==
==Analysis of Insertion Sort==
Consider the following insertion sort algorithm:
<pre>
for(i=1; i<n; i++) {
    j = i;
    while((j>0)&&(s[j]<s[j-1])) {
        swap(&s[j],&s[j-1]);
        j=j-1;
    }
}
</pre>

Revision as of 07:33, 28 May 2017

Analysis of Selection Sort

Consider the following selection sort algorithm:

selection_sort(int s[], int n)
{
    int i, j; // counters
    int min; // index of minimum

    for(i=0; i<n; i++) {
        min = i;
        for(j=i+1; j<n; j++) 
          if(s[j] < s[min]) min = j;
        swap(&s[i], &s[min]);
    }
}

performing the algorithmic analysis:

  • for loop with i index operates O(n) times
  • second for loop operates O(i) times, within the loop that runs n times, for an algorithmic complexity given below.

$ O(i) : \sum_{i=1}^{n} i = \dfrac{n(n+1)}{2} \sim O(n^2) $

Overall this algorithm is quadratic.

Analysis of Insertion Sort

Consider the following insertion sort algorithm:

for(i=1; i<n; i++) { 
    j = i;
    while((j>0)&&(s[j]<s[j-1])) {
        swap(&s[j],&s[j-1]);
        j=j-1;
    }
}