Skip to main content
ICT
Lesson AB25 - Order of Algorithms
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

F. Quadratic Algorithms, (N2) page 8 of 11

  1. This is an algorithm, seen in line E on the Order of Algorithms graph, in which the number of steps required to solve a problem increases as a function of N2. For example, here is bubbleSort.

    void bubbleSort(ArrayList <Comparable> list){
      for (int outer = 0; outer < list.length - 1; outer++){
        for (int inner = 0; inner < list.size()-outer-1; inner++){
          if (list.get(inner).compareTo(list.get(inner + 1) > 0){
            //swap list[inner] & list[inner+1]
            Comparable temp = list.get(inner);
            list.set(inner, list.get(inner + 1));
            list.set(inner + 1, temp);
          }
        }
      }
    }

  2. The if statement is buried inside nested loops, each of which is tied to the size of the data set, N. The if statement is going to be executed approximately N times for each of N items, or N2 times in all.

  3. The efficiency of this bubble sort was slightly improved by having the inner loop decrease, but we still categorize this as a quadratic algorithm.

  4. For example, the number of times the inner loop happens varies from 1 to (N-1). On average, the inner loop occurs (N/2) times.

  5. The outer loop happens (N-1) times, or rounded off N times.

  6. The number of times the if statement is executed is equal to this expression:

    # if statements = (Outer loop) * (Inner loop)
    # if statements = (N) * (N/2)
    # if statements = N2/2

  7. The coefficient 1/2 becomes insignificant for large values of N, so we have an algorithm that is quadratic in nature.

  8. When determining the order of an algorithm, we are only concerned with its category, not a detailed analysis of the number of steps.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.