【问题标题】:Bubble sorting a file in C在C中对文件进行冒泡排序
【发布时间】:2015-09-13 16:36:48
【问题描述】:

我编写了一个程序,它连接到服务器并从中接收代码行,然后将所有代码行打印到文本文件中,问题是,服务器不按顺序发送所有代码行,我的意思是是在包含代码行的文本文件中没有顺序,它可以是第 55 行,在第 33 行之后,我正在尝试编写一个对文件进行排序的函数,因此代码行将按顺序排列,我知道我需要使用冒泡排序并将字符串中的行号转换为int,但我之前从未尝试过对文本文件进行冒泡排序,这是我的代码:(忽略注释)

#define  _WINSOCK_DEPRECATED_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<winsock2.h>
#include<windows.h>
#include<string.h>


#define LEN 1024

void sortcode(FILE *fp);
int main(void)
{
    FILE *fp;
    fp = fopen("theCode.txt", "wt");
    int i;
    WSADATA info;
    char str[LEN];
    str[LEN - 1] = NULL;
    char str2[LEN];
    str2[LEN - 1] = NULL;
    char temp[8] = "5000000"; // the row number
    int j = strlen(temp) - 1;// the index of the temp string
    int k = 0;
    int err;
    err = WSAStartup(MAKEWORD(2, 0), &info);
    if (err != 0)
    {
        printf("WSAStartup failed with error: %d\n", err);
        exit(1);
    }
    int s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (s == INVALID_SOCKET)
    {
        printf("Error creating socket = %d\n", WSAGetLastError());
    }
    else
    {
        printf("Socket function succeeded\n");
    }
    struct sockaddr_in clientService;
    clientService.sin_family = AF_INET;
    clientService.sin_addr.s_addr = inet_addr("54.152.161.133");
    clientService.sin_port = htons(6714);
    int cResult = connect(s, (struct socketaddr*)&clientService, sizeof(clientService));
    if (cResult == SOCKET_ERROR)
    {
        printf("Connect function failed with error: %d\n", WSAGetLastError());
        cResult = closesocket(cResult);
        if (cResult == SOCKET_ERROR)
        {
            printf("Close socket function closed with an error: %1d\n", WSAGetLastError());
        }
        WSACleanup();
        //return 1;
    }
    //Until this part, it's all taken from the slideshow.
    send(s, "100", LEN, 0); //Sending code 100: Requesting to connect.
    printf("Request to connect was sent using 100\n");
    recv(s, str, LEN, 0); //Recieving a code to the string str.
    printf("Code recieved: %s\n", str);
    if (strcmp("101", str) == 0)
    {
        printf("Connection was successful\n");
    }
    else
    {
        printf("The connection failed\n");
    }
    send(s, "400", LEN, 0); //Sending a request for the number of code lines.
    printf("Request for the amount of code lines was sent using 400\n");
    recv(s, str, LEN, 0); //Recieving the answer on str, you'll get code 401+The number of lines for example 4010079.
    printf("String recieved: %s\n", str);
    printf("The amount of code lines: 0079\n");
    printf("%s", str);
    for (k = 1; k <= 7; k++)
    {
        for (i = 0; i <= 9; i++)
        {
            temp[j] = i + 0x30;
            send(s, temp, LEN, 0);
            recv(s, str, LEN, 0);
            fprintf(fp, str);
            fprintf(fp, "\n");
        }
        temp[j - 1] = k + 0x30;
        temp[j] = 0 + 0x30;
    }
    //You need to add the part with the files where you print all the lines including the code in them to a txt file.
    //Good Luck, first try to solve that i to string conversion.
    system("PAUSE");
    return (0);
}
void sortcode(FILE *fp)
{
    int i, j, k;
    char str2[LEN];
    fp = fopen("theCode.c", "rt");
    for (i = 0; i < 79; i++)
    {
        for (j = 3; j < 7; j++)
        {

        }
    }
}

【问题讨论】:

  • 为什么需要使用冒泡排序,而不是标准库qsort() 函数?在许多方面,学习如何使用标准排序比编写自己的排序更好。
  • Bubble Sort Homework 的可能重复项
  • OT:在#include 后面加一个空格不再流行了吗?我已经看到很多 C 代码发布到 SO 中省略了空格,我不知道为什么。
  • @SeanBright:风格不好;标准没有这样做,程序员也不应该这样做。是的,这很常见——令人沮丧的常见。但这并不明智。
  • “我知道我需要使用冒泡排序” - 不,冒泡排序几乎不合适 - 只需使用 C 库中的 qsort。

标签: c windows file casting bubble-sort


【解决方案1】:

您可以将整个文件读入一个行数组。然后你可以在 stdlib.h 中使用 qsort() 对你的数组进行排序。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

static int compare_lines( const void* left, const void* right )
{
    const char* l = *((char**)left);
    const char* r = *((char**)right);
    return strcmp( l, r );
}

int main(int argc, char* argv[])
{
    char** lines           = NULL;
    size_t number_of_lines = 0;

    const char* fruits[] = {
        "Banana",
        "Orange",
        "Ugli Fruit",
        "Pomegranate",
        "Peach",
        "Apple",
        "Blueberry",
        "Raspberry",
        "Guava",
        "Cherry",
        "Star Fruit",
        "Pomelo",
        "Kiwi",
        "Pineapple",
        "Fig",
        "Papaya"
    };

    size_t len = sizeof(fruits) / sizeof(fruits[0]);

    for( size_t i = 0; i < len; i++ )
    {
        void* p = realloc( lines, (number_of_lines + 1) * sizeof(char*) );
        if( p ) lines = p;
        else goto done;

        lines[ number_of_lines ] = malloc( strlen(fruits[ i ]) + 1 );
        strcpy( lines[ number_of_lines ], fruits[ i ] );
        number_of_lines++;
    }

    qsort( lines, number_of_lines, sizeof(char*), compare_lines );


    for( size_t i = 0; i < number_of_lines; i++ )
    {
        printf( "%zu.) %s\n", i, lines[ i ] );
    }

done:
    if( number_of_lines > 0 && lines )
    {
        for( size_t i = 0; i < number_of_lines; i++ ) free( lines[ i ] );
        free( lines );
    }
    return 0;
}

编辑:修复了 compare_lines() 中的指针错误。

【讨论】:

  • 比较器被赋予指向两个要比较的值的指针;把一个想象成左边一个,另一个在右边。如果左侧排序在右侧之前,比较器必须返回负值,如果左侧排序在右侧之后,则比较器必须返回正值,如果值排序相同,则比较器必须返回零。不过,我还不相信答案中的代码是正确的。我想我希望使用char *lhs = *(char **)left; char *rhs = *(char **)right; return strcmp(lhs, rhs);——但我没有通过执行它来仔细检查。请注意,对qsort() 的调用需要在函数中。
  • 行号需要用 0 填充并且长度相同(我们不知道),否则需要从文本中提取行号。
  • 我查过了。这个比较器工作正常:static int compare(const void *p_lhs, const void *p_rhs) { const char *lhs = *(char **)p_lhs; const char *rhs = *(char **)p_rhs; return strcmp(lhs, rhs); }。测试你的;我认为这不会是正确的。 (它没有崩溃,但字符串不是我认为的排序顺序。)
  • 哇。我去吃午饭,每个人都在根据 MISRA 规则检查和运行我的 sn-p。大声笑我的 sn-p 旨在引导@Jokerah 朝着正确的方向前进。
  • 发布不准确的代码没有帮助——午餐时间或没有。你会注意到你没有得到净反对票(还)。请注意您的回答并显示正确的工作代码。
【解决方案2】:

即使您决定编写自己的排序函数而不是使用qsort(),冒泡排序算法对于少数几个项目来说也是一个非常糟糕的选择。

如果您愿意缓冲内存中的所有行,直到您读取并排序所有行,这可能是您最好的选择,那么您应该考虑随时对它们进行排序。每次阅读新行时,在已阅读的行中找到它的位置,并将其插入那里。这本质上是一种插入排序。

如果您希望您的行大部分是有序的,那么从后到前线性搜索每个插入点。这是标准的插入排序,它对于近似有序的输入非常有效。对于没有特定顺序的大量行,您可以考虑使用二进制搜索来查找每个插入点。

如果您使用链表来保存行(如果您事先不知道会有多少行,这是一个合理的选择),那么二进制搜索替代方案可以很好地扩展到大型输入。

【讨论】:

  • 谢谢,我遇到的一些问题是在文本文件中,有行号,后面是行号,因为它是字符串类型,我需要转换它将它转换为 int 以便我可以检查一个行号是否大于另一个行号,因为我正在尝试对一个文本文件进行排序,这对我来说是新的东西我有点挣扎,我习惯于对数组进行排序并且我正在尝试实现它对文本文件进行排序。
  • @Jokerah:首先要做的事情(在更正 'received' 的拼写之后 - 'i' 在 'e' 之前,除了 'c' 之后)是打印要排序的数据。在问题中显示该数据。这将帮助人们帮助你。但这意味着您需要一个比较器函数来正确处理字符串的格式。例如,它可能使用atoi() 将字符串转换为数字——如果行号总是唯一的,它可能永远不需要比较字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-19
  • 2013-06-10
  • 2021-09-16
  • 2016-01-01
  • 1970-01-01
相关资源
最近更新 更多