【问题标题】:Bubblesort with C用 C 冒泡排序
【发布时间】:2012-10-02 15:43:51
【问题描述】:

我有一个非常简单(或至少应该是)的任务,我必须对大量随机数运行冒泡排序并查看其执行时间。然后我必须做同样的事情,除了将数组分成两半,一半在一个线程中排序,另一半在另一个线程中排序,看看这样是否更快。

我以前从未使用过 C,所以我对指针一无所知,只使用过 Java。这是我的代码,因为我只是想让冒泡排序工作。

#include <string.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <libgen.h>

int main() {
  int *array[50000];
  for(int i = 0; i < 50000; i++) {
    array[i] = 1;
  }
  bubbleSort(array, 50000);
}

void bubbleSort(int *numbers[], int *array_size) {
  int i, j, temp;
  for(i = (array_size - 1); i > 0; i--) {
    for(j = 1; j <= i; j++) {
  if(numbers[j-1] > numbers[j]) {
    temp = numbers[j-1];
    numbers[j-1] = numbers[j];
    numbers[j] = temp;
      }
    }
  }
  for(int i = 0; i < 10; i++) {
    printf(numbers[i]);
  }
}

我在这里要做的就是对数组进行排序,然后打印出前十个数字,这样我就知道它正在工作。我收到各种指针错误。

"bubbleSort.c", line 11: warning: improper pointer/integer combination: op "="
"bubbleSort.c", line 13: warning: implicit function declaration: bubbleSort
"bubbleSort.c", line 16: identifier redeclared: bubbleSort
        current : function(pointer to pointer to int, pointer to int) returning void
        previous: function() returning int : "bubbleSort.c", line 13
"bubbleSort.c", line 18: warning: improper pointer/integer combination: op "="
"bubbleSort.c", line 21: warning: improper pointer/integer combination: op "="
"bubbleSort.c", line 23: warning: improper pointer/integer combination: op "="
"bubbleSort.c", line 28: warning: argument #1 is incompatible with prototype:
        prototype: pointer to const char : "/usr/include/iso/stdio_iso.h", line 206
        argument : pointer to int
cc: acomp failed for bubbleSort.c

【问题讨论】:

  • array[i] = 1; 我知道,由公平掷骰决定,但这并不是测试性能的“随机数数组”的意思。
  • 哎呀,我已经更改了这个,因为我收到了一个错误并且忘记在发布之前将其更改回来。我在那里有 rand() 而不是一个,但它不喜欢那样。让我现在把它改回来,看看错误是什么。

标签: c unix bubble-sort


【解决方案1】:

这个:

int *array[50000];

声明一个包含 50,000 个元素的指向 int 的指针数组,这可能不是您想要的。删除*

bubbleSort() 原型中,您还拥有应该删除的虚假星号。

请注意,星号表示 C 语言中的某些东西,你不应该只是随意地用它们来装饰你的代码,无论你喜欢什么。如果您不确定什么以及何时,如果这是针对课程的,您应该可以访问一些教程信息。开始阅读。

【讨论】:

  • 我最初在没有指针的情况下完成了这一切。如果可能的话,我想避免它们。不幸的是,这不是一门介绍性课程,我们有点被扔进火里,希望知道 C。当我从数组和 bubbleSort 方法的参数中删除星号时,这是我得到的错误导致我相信我需要星号。 code"bubbleSort.c",第 16 行:标识符重新声明:bubbleSort 当前:函数(指向 int,int 的指针)返回 void 先前:函数()返回 int:“bubbleSort.c”,第 13 行 code
【解决方案2】:

第 11 行:您不应该声明 int *array[],而应该声明 int array[]
第 13 行:原型化您的函数或在 main 上方声明它
第 16 行:您声明了 int *array_size,但主要是给它一个 int
第 18、21 和 23 行:11 相同.
第 28 行:永远不要将 printf 与可变格式字符串一起使用! printf("%i, ", numbers[i]); 就是这样。

您真的应该复习 C 编码基础知识

【讨论】:

  • 谢谢。似乎只有几件事与我习惯的语言不同,我还有一些工作要做。再次感谢。
猜你喜欢
  • 2014-03-26
  • 2018-11-13
  • 1970-01-01
  • 2014-02-25
  • 2017-06-21
  • 2012-07-19
  • 2015-09-06
  • 2013-03-09
  • 2013-01-23
相关资源
最近更新 更多