Jonathan Gruver - 5 days ago 5
Java Question

# Array Sort Stops Too Soon

I'm trying to create two classes, one to define a point and another for array operations. I'm trying to create a method to sort an array of coordinates in ascending order based on y coordinates. I've tried following examples, but I keep running into a runtime error where the array is only partially sorted.

public class Point
{
private double x;
private double y;

public Point(double x_coord, double y_coord)
{
x = x_coord;
y = y_coord;
}
public boolean lessThan(Point anotherPoint)
{
if(y < anotherPoint.y)
{
if(x < anotherPoint.x)
{
return true;
}
}
return false;
}
}
public class PointArray
{
private Point[] points = new Point[count];

public PointArray(double[] doubleArray)
{
if(doubleArray.length % 2 == 0)
{
for(int i = 0, j = 0; i < 3; i++, j += 2)
{
double x = doubleArray[j];
double y = doubleArray[j + 1];
points[i] = new Point(x, y);
}
}
else
{
System.out.println("Error: The given array must be even.");
System.exit(0);
}
}
public void sort()
{
double x = 0;
double y = 0;
Point newPoint = new Point(x, y);
Point temp = new Point(x, y);
for (int i = 0; i < points.length - 1; i++)
{
for(int j = i + 1; j < points.length; j++)
{
int minIndex = i;
if(points[minIndex].lessThan(points[j]) == false)
{
temp = points[minIndex];
points[minIndex] = points[j];
points[j] = temp;
}
}
}
}

This code causes the array
{5.6, 7.1, 4.9, 13.17, 9.3, 2.9}
to first be stored as ordered pairs
{(5.6, 7.1), (4.9, 13.17), (9.3, 2.9)}
. but it does not sort them properly. After the first and third points are swapped, the second and third are not, even though the y coordinate of the third is smaller.

[(9.3, 2.9), (4.9, 13.17), (5.6, 7.1)]