This is an old revision of the document!


Lab 05 - Recurrences

1. Basic algorithms

1.1 Based on the following code for Bubble-sort, analyze the algorithm's time complexity:

  void bubbleSort(int arr[], int n)
  {
      int i, j, temp;
      for(i = 0; i < n; i++)
      {
          for(j = 0; j < n-i-1; j++)
          {
              if( arr[j] > arr[j+1])
              {
                  // swap the elements
                  temp = arr[j];
                  arr[j] = arr[j+1];
                  arr[j+1] = temp;
              } 
          }
      }
  }

1.2 Based on the following code for Insertion sort, analyze the algorithm's time complexity:

  void insertionSort(int arr[], int n)  
  {  
      int i, key, j;  
      for (i = 1; i < n; i++) 
      {  
          key = arr[i];  
          j = i - 1;  
    
          /* Move elements of arr[0..i-1], that are  
          greater than key, to one position ahead  
          of their current position */
          while (j >= 0 && arr[j] > key) 
          {  
              arr[j + 1] = arr[j];  
              j = j - 1;  
          }  
          arr[j + 1] = key;  
      }  
  }

2. Simple Recurrences

Consider the following search algorithm of a value v in a sorted array arr:

  int search (int arr[], int lo, int hi, int v){
      int mid = (lo+hi)/2;  
      if (arr[mid] == v)
          return mid;
      if (lo == hi)
          return -1;
      if (arr[mid] > v)
          return search(arr, lo, mid, v);
      else
          return search(arr, mid, hi, v);
  }

2.1 Determine the recurrence for the search algorithm above.

1.2 Solve the recurrence using the Master Method.

1.3 Solve the recurrence using the Trees Method.

1.4 Solve the recurrence using the Substitution Method.