So I tried implementing my Quicksort for sorting an array of Edges by their weight which is in int for my Kruskal’s algorithm implementation. Is there a built function in javascript for sorting an array of objects by their properties? In this case by their weight. From smallest weight to the largest.
Here is my edge class.
class Edge
{
private int u;
private int v;
private int weight;
public Edge(int i, int i2, int w)
{
u = i;
v = i2;
weight = w;
}
public int getU() {
return u;
}
public int getV() {
return v;
}
public int getWeight() {
return weight;
}
}
Kruskal’s code
class MSTKruskal
{
Edge[] mst(int[][] G)
{
Edge A[] = new Edge[G.length - 1];
Forest aForest = new Forest(G.length);
Edge E[] = new Edge[(G.length * G.length - G.length)/2];
int i3 = 0;
for (int i = 0; i < G.length; i++)
{
for(int i2 = i+1; i2 < G.length; i2++)
{
Edge anEdge = new Edge(i, i2, G[i][i2]);
E[i3] = anEdge;
i3++;
}
}
print(E);
//QuickSort(E, 0, E.length);
print(E);
int index = 0;
for (int i = 0; i < E.length; i++)
{
if (aForest.findSet(E[i].getU()) != aForest.findSet(E[i].getV()))
{
A[index] = E[i];
index++;
aForest.union(E[i].getU(), E[i].getV());
}
}
aForest.printA();
return A;
}
In javascript you can pass function as parameter to sort method, this function should take 2 parameters (a and b), and return:
In your case it should be something like:
So you can easily sort by any arrays contents’ properties or even more complex criteria.