Consider a coordinate system for the Milky Way, in which the Earth is at (0; 0; 0). Model stars as points, and assume distances are in light years. The Milky Way consists of approximately 1012 stars, and their coordinates are stored in a file in comma-separated values (CSV) format—one line per star and four fields per line, the first corresponding to an ID, and then three floating point numbers corresponding to the star location. How would you compute the k stars which are closest to the Earth? You have only a few megabytes of RAM.
Asked
Active
Viewed 179 times
0
-
1What is the purpose of finding another way to solve it? Is it speeding up the calculations or reducing memory consumption? – bit Apr 15 '15 at 03:44
-
I'm just curious to see if there is any other way to solve this without using heapsort, and if that way can speed up the calculations or reduce memory consumption, that would be even better. – Harper Sue Apr 15 '15 at 03:46
-
You may try using LINQ, there is an out of the box method to find the Min() of a given IEnumerable . – bit Apr 15 '15 at 03:47
-
There are lots of ways to sort an array, just ask Google... – Rufus L Apr 15 '15 at 04:11
-
Do we need to find one minimum element or k? – Orifjon Apr 15 '15 at 04:42
-
Possible duplicate of http://stackoverflow.com/questions/5380568/algorithm-to-find-k-smallest-numbers-in-array-of-n-items – Alex Apr 15 '15 at 04:50
2 Answers
0
You could skip the sorting altogether and use the Linq extension method: Min()
:
var distanceArray = new int[] {10, 2, 453, 134, 22, 78, 2424, 12,
5, 23232, 6442, 64, 99564, 1314, 20 };
int actual = distanceArray.Min();
int expected = 2;
Assert.AreEqual<int>(expected, actual);

Rufus L
- 36,127
- 5
- 30
- 43
0
Another way to do it would be to just walk through the array without sorting it, looking for the smallest item. Of course this is easy for a single item, slightly harder for 'n' number of items. As 'n' grows, sorting becomes more desirable.
int[] distanceArray = new int[] { 10, 2, 453, 134, 22, 78, 2424, 12,
5, 23232, 6442, 64, 99564, 1314, 20 };
int actual = int.MaxValue;
foreach (int distance in distanceArray)
{
if (distance < actual) actual = distance;
}
int expected = 2;
Assert.AreEqual<int>(expected, actual);

Rufus L
- 36,127
- 5
- 30
- 43
-
You may want to add a third answer, as the question mentions " ... the **k** ... stars". I.e. OP did have the right approach, but a poor code example for "k = 1". – Alex Apr 15 '15 at 04:42