Someone on reddit had a small Computer Science question that was, to be quite honest, stupid simple with a bit of reasoning. They deleted their post (good on them really) before I could give them my answer, so here it is for you.
Q: "A sort (such as a bubble sort or insertion sort) is O(n2). 1000 records are sorted in 1 second. How long does it take to sort 3000 records?"
Can someone explain "O(n2)" to me? please? :)
I'm studying for a final in an intro to comp sciences class, and something that I never understood was this O(n2) thing.
The example he gives is of sorting records. On the last (midterm) exam, the question arose:
"A sort (such as a bubble sort or insertion sort) is O(n2). 1000 records are sorted in 1 second. How long does it take to sort 3000 records?"
I could not for the life of me figure out how he came to 1 second from 1000 records. (and I got the answer wrong :\ )
Could anyone explain this to me, pretty please? I'd appreciate it!
A: 9 seconds.
n is the number of records to deal with. O(n^2) means that running time will be exponential. In other words, for 3000 records your program will execute the inner loop body 3000^2 or 9,000,000 times.
Luckily, your prof gave you a rate. Unfortunately, the dim-witted will think this is linear and say, "1000 records in a sec, then it'll be 3 secs for 3000!" which is quite wrong.
Keeping in mind that when n = 1000 then n^2 = 1,000,000. According to the problem, 1,000,000 operations takes 1 second, so the sort on 3000 items should take 9 seconds.