Sept 14, 2022
for(i ← 0 until n) { /* do work */ }
Total Runtime: 7/10 of original (30% faster)
... but still Θ(n)
Compare T1(n)=100n vs T2(n)=n2
Asymptotically slower runtimes can be better.
... but from now on, if T2(n) is in a bigger complexity class, then T1(n) is better/faster/stronger.
bubblesort(seq: Seq[Int]):
1. n ← seq length
2. for i ← n-2 to 0, by -1:
3. for j ← i to n-1:
4. if seq(j+1) < seq(j):
5. swap seq(j) and seq(j+1)
What is the runtime complexity class of Bubble Sort?
bubblesort(seq: Seq[Int]):
1. n ← seq length
2. for i ← n-2 to 0, by -1:
3. for j ← i to n-1:
4. if seq(j+1) < seq(j):
5. swap seq(j) and seq(j+1)
Note: We can ignore the exact number of steps required by any step in the algorithm, as long as we know its complexity
Can we safely say this algorithm is Θ(n2)?
def sort(seq: mutable.Seq[Int]): Unit =
{
val n = seq.length
for(i <- n - 2 to 0 by -1; j <- i to n)
{
if(seq(n) < seq(j))
{
val temp = seq(j+1)
seq(j+1) = seq(j)
seq(j) = temp
}
}
}
def sort(seq: Seq[Int]): Seq[Int] =
{
val newSeq = seq.toArray
val n = seq.length
for(i <- n - 2 to 0 by -1; j <- i to n)
{
if(newSeq(n) < newSeq(j))
{
val temp = newSeq(j+1)
newSeq(j+1) = newSeq(j)
newSeq(j) = temp
}
}
return newSeq.toList
}
def indexOf[T](seq: Seq[T], value: T, from: Int): Int =
{
for(i <- from until seq.length)
{
if(seq(i).equals(value)) { return i }
}
return -1
}
def count[T](seq: Seq[T], value: T): Int =
{
var count = 0;
var i = indexOf(seq, value, 0)
while(i != -1)
{
count += 1;
i = indexOf(seq, value, i+1)
}
return count
}
... with O(1) access to elements ('random access')
What if no random access is available?