Hello,
I am working on a project that requires a set of points to be sorted by their angles in relation to the x-axis. The angles, which are in radians, store their angle as a double value. My insertion sort algorithm is failing to properly sort the points based on angle roughly 30% of the time. The output is as follows:

PointX, PointY, Angle
673 136 0.0
567 468 1.879843390364502
480 251 2.604226578944233
850 540 1.1578666070408863
461 529 2.0654960756691922
540 70 2.680957083672938

private static void sortAngles(point [] points)
{
	int index;
	double smallest;
	point temp;
	for(int i = 0; i < points.length; i++)
	{
		index = i;
		smallest = points[i].getAngle();
		for(int j = i + 1; j < points.length; j++)
		{
			if(smallest > points[j].getAngle())
			{
				index = j;
			}
		}
		temp = points[index];
		points[index] = points[i];
		points[i] = temp;
	}
}

The ">" operator seems to be failing but I'm not sure. I realize that doubles will only store estimates of the true angle but they should be able to be compared correctly. Any suggestions?

> My insertion sort algorithm is failing to properly sort the points
> based on angle roughly 30% of the time.

That isn't an Insertion sort which you are trying to implement; also whichever algorithm that is, it's broken. Try it for input [5, 8, 1, 2].

Read this.

Thanks ~s.o.s~! I incorrectly stated insertion sort whenever it is actually selections sort I believe. Either way I discovered that the reason it isn't working is simply because I never change smallest; it stays the same throughout the entire scan no matter what. Problem solved! Thanks!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.