Today's objective is to create a function that takes in a sorted array and a new value to insert in to that array. The function should then insert the value in sorted order and return back the array with the new value. Your function should figure out where to insert the new value in better than O(n) time (on average).
Comments:
Anonymous - 10 years, 6 months ago
reply permalink
Nick Krichevsky - 10 years, 6 months ago
Done. I figured mine should come with a joke today. Two men walk into a bar. Ouch. (Did I ever mention I was terrible at jokes?)
reply permalink
bumbleguppy - 10 years, 6 months ago
This was my first thought as well, just iterate through each list item and compare. But I was concerned about the operation time had to be better than O(n).
Since I don't have a CS degree, I had to look up what O(n) meant, and found this:
http://rob-bell.net/2009/06/a-beginners-guide-to-big-o-notation/
I am intrigued by the "binary search" concept.
Could I write something that finds the middle value and then compares the input to it? i.e. "is it in the first half or second half of the list?"
That way I halve HALVED the number of operations right off the bat! :)
Sill working on it, though.
reply permalink
Max Burstein - 10 years, 6 months ago
Nicely done. Binary search is indeed the correct way to approach this problem.
reply permalink
bumbleguppy - 10 years, 6 months ago
I think I've got it now in javascript:
reply permalink
bumbleguppy - 10 years, 6 months ago
Oops, fails when value is lower than first element :(
reply permalink
Mre64 - 10 years, 6 months ago
/* Mre64 6/17/14
*/ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List;
public class InsertSort {
}not a lot of time so i cheated hard today
reply permalink