C Programming: Sorting Edges with Two Nodes
To get the sorted nodes of edges with two nodes in C, you can use a struct to represent the edge and an array to store all the edges. Here's an example implementation:
c
#include <stdio.h>

typedef struct {
 int node1;
 int node2;
} Edge;

void sortEdges(Edge edges[], int numEdges) {
 for (int i = 0; i < numEdges; i++) {
 for (int j = i + 1; j < numEdges; j++) {
 if (edges[i].node1 > edges[j].node1 || (edges[i].node1 == edges[j].node1 && edges[i].node2 > edges[j].node2)) {
 Edge temp = edges[i];
 edges[i] = edges[j];
 edges[j] = temp;
 }
 }
 }
}

int main() {
 Edge edges[] = {
 {3, 1},
 {2, 4},
 {1, 2},
 {5, 3},
 {4, 5}
 };
 int numEdges = sizeof(edges) / sizeof(edges[0]);

 sortEdges(edges, numEdges);

 printf("Sorted edges: ");
 for (int i = 0; i < numEdges; i++) {
 printf("(%d, %d) ", edges[i].node1, edges[i].node2);
 }

 return 0;
}

In this example, the Edge struct has two integer fields node1 and node2 to represent the two nodes of an edge. The sortEdges function uses a simple bubble sort algorithm to sort the edges based on the values of node1 and node2. Finally, the sorted edges are printed in the main function.
原文地址: https://www.cveoy.top/t/topic/pyyX 著作权归作者所有。请勿转载和采集!