To sort segments with two nodes in C, you can use the bubble sort algorithm. Here's an example implementation:

#include <stdio.h>

// Structure to represent a segment with two nodes
typedef struct {
    int node1;
    int node2;
} Segment;

// Function to swap two segments
void swap(Segment* a, Segment* b) {
    Segment temp = *a;
    *a = *b;
    *b = temp;
}

// Function to perform bubble sort on an array of segments
void sortSegments(Segment segments[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            // Compare the two nodes of the segments
            if (segments[j].node1 > segments[j + 1].node1) {
                swap(&segments[j], &segments[j + 1]);
            }
        }
    }
}

int main() {
    // Example segments
    Segment segments[] = {
        {2, 1},
        {5, 3},
        {4, 6},
        {1, 9},
        {3, 7}
    };
    int n = sizeof(segments) / sizeof(segments[0]);

    printf("Segments before sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("(%d, %d) ", segments[i].node1, segments[i].node2);
    }
    printf("\n");

    sortSegments(segments, n);

    printf("Segments after sorting:\n");
    for (int i = 0; i < n; i++) {
        printf("(%d, %d) ", segments[i].node1, segments[i].node2);
    }
    printf("\n");

    return 0;
}

This code defines a Segment structure to represent a segment with two nodes. The swap function is used to swap two segments, and the sortSegments function performs bubble sort on an array of segments. Finally, the main function demonstrates the usage by sorting an example array of segments and printing the sorted result.

Note that the sorting is based on the node1 field of the segments. If you want to sort based on node2 or any other criteria, you can modify the comparison condition inside the sorting loop accordingly

C sort segments with two nodes

原文地址: https://www.cveoy.top/t/topic/hPqD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录