Wednesday, February 26, 2020

Time Complexity


Example 1
  1. x = n
  2. while ( x > 0 ) {
  3. x = x - 1
  4. }

The above is O(n)

Example 2
  1. x = n
  2. while ( x > 0 ) {
  3. x = x / 2
  4. }

The above is O(logn)

Example 3
  1. x = n
  2. while ( x > 0 ) {
  3. y = n
  4. while ( y > 0 ) {
  5. y = y - 1
  6. }
  7. x = x - 1
  8. }

The above is O(n2)

Example 4
  1. x = n
  2. while ( x > 0 ) {
  3. y = x
  4. while ( y > 0 ) {
  5. y = y - 1
  6. }
  7. x = x - 1
  8. }

The above is O(n2)

Example 5
  1. x = n
  2. while ( x > 0 ) {
  3. y = n
  4. while ( y > 0 ) {
  5. y = y / 2
  6. }
  7. x = x - 1
  8. }

The above is O(nlogn)

Example 6
  1. x = n
  2. while ( x > 0 ) {
  3. y = x
  4. while ( y > 0 ) {
  5. y = y / 2
  6. }
  7. x = x - 1
  8. }

The above is O(nlogn)

Example 7
  1. x = n
  2. while ( x > 0 ) {
  3. y = n
  4. while ( y > 0 ) {
  5. y = y - 1
  6. }
  7. x = x / 2
  8. }

The above is O(nlogn)

Example 8
  1. x = n
  2. while ( x > 0 ) {
  3. y = x
  4. while ( y > 0 ) {
  5. y = y - 1
  6. }
  7. x = x / 2
  8. }

The above is O(n)

Example 9
  1. x = n
  2. while ( x > 0 ) {
  3. y = n
  4. while ( y > 0 ) {
  5. y = y / 2
  6. }
  7. x = x / 2
  8. }

The above is O(log2n)

Example 10
  1. x = n
  2. while ( x > 0 ) {
  3. y = x
  4. while ( y > 0 ) {
  5. y = y / 2
  6. }
  7. x = x / 2
  8. }

The above is