34D. Example Algorithms

Here are some sample worst case times used by a few algorithms, expressed as functions of the size n of the problem.

  1. To add up all of the members of an array that has n members takes time Θ(n). (You do one addition per number in the array. Each addition takes a constant amount of time.)

  2. To compute the length of a linked list takes time Θ(n), where n is the list length. (You need to look at each cell once as you traverse the list.)

  3. To compute strlen(s) for a null-terminated string x takes time Θ(n), where n is the string length. (Strlen counts the characters.)

  4. To sort a linked list using Insertion Sort takes time Θ(n2), where n is the length of the list. (Insertion Sort does an insertion for each member of the list. Each insertion takes time proportional to the length of the list that it inserts into. If you do n steps and each step takes time proportional to n, then the total time is proportional to n2.)

  5. Later, we will see an algorithm called Heapsort that sorts an array of n integers in time Θ(nlog(n)). That is much faster than Insertion Sort.

    It might appear that it is cheaper to sort an array than to sort a linked list. The real difference is in the algorithm, not in how the information is represented.)


Exercises

  1. Using Θ notation, say how much time the following function uses, as a function of the length n of string s.

      char* vowels = "aeiouAEIOU";
    
      int numVowels(char* s)
      {
        int count= 0;
        for(int i = 0; s[i] != '\0'; i++)
        {
          if(strchr(vowels, s[i]) != NULL)
          {
            count++;
          }
        }
        return count;
      }
    
    Answer

  2. Same as the preceding question, but for the following function.

      char* vowels = "aeiouAEIOU";
    
      int numVowels(char* s)
      {
        int count= 0;
        for(int i = 0; i < strlen(s); i++)
        {
          if(strchr(vowels, s[i]) != NULL)
          {
            count++;
          }
        }
        return count;
      }
    
    Answer