【问题标题】:User input in bubble sort冒泡排序中的用户输入
【发布时间】:2012-07-21 16:29:43
【问题描述】:

我正在尝试编写一个代码,让用户编写自己的数字并决定他是否希望它们按升序或降序排序,并使用冒泡排序对它们进行排序。这是我目前能写的(又名明显的入口);

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

int main()
{
  int n, a, number;
  printf("Enter your numbers. Write -1 to stop. \n");
  do {
    scanf("%d", &a);
  } while(a != -1);
  printf("Enter 1 if you want them to be in ascending order. Enter 2 if you want  descending order\n");
  scanf("%d", &a);
  if(a = 1)
    do {
      system("PAUSE");
      return 0;
    }

我的问题是,我真的不知道如何合并冒泡排序。在所有示例中,我都可以找到事先设置好的数组。我想我应该从 for 结构开始,但我不知道。

编辑:

多亏了帮助,我才走到了这一步,它有点“工作”,直到我写 1 或 2 然后它崩溃了。有什么建议吗?

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

int main()
{
int myarray[100],index,a,b,swap,turn;
index=0;
printf("Enter your numbers. Write -1 to stop. \n");
do{
            scanf("%d", &myarray[index]);
            index++;
            }while(myarray[index-1] != -1);
printf("Enter 1 if you want them to be in ascending order. Enter 2 if you want   descending order\n");
scanf("%d",&b);
if(b == 1) {
   for(turn=1; turn <= myarray[100] -1; turn++)

   for(index = 0; index <=  myarray[100]; index++)
   {
   if (myarray[index] > myarray[index+1]){ 
    swap  = myarray[index];
    myarray[index]   = myarray[index+1];
    myarray[index+1] = swap; }
    }
}
else {
   for(turn=1; turn <= myarray[100] -1; turn++)

   for(index = 0; index <=  myarray[100]; index++)
   {
   if (myarray[index] < myarray[index+1]){ 
    swap  = myarray[index];
    myarray[index]   = myarray[index+1];
    myarray[index+1] = swap; }
    }
}   
system("PAUSE");
return 0;
} 

【问题讨论】:

  • myarray[100] 的访问超出范围。

标签: c sorting bubble-sort


【解决方案1】:

您是正确的,因为您需要将这些数字存储在某种数据结构中,例如数组或向量。向量是一个不错的选择,因为您不知道用户将输入多少个数字。这是您可以应用于您的代码的草图:

#include <vector>

int main()
{
  // ...
  std::vector<int> userInts;
  // ... get input 
  userInts.push_back(a); // add int to the end of the list

  bubbleSort(userInts);
  // ...
}

编辑:我没有意识到这被标记为 C 而不是 C++。只需将std::vector 调用换成一些代码即可在C(或您自己的向量实现)中动态分配一个数组。或者,如果您知道只有 N 个整数将被输入,则声明 int userInts[N],循环输入,将其插入数组,然后排序。

EDITx2:请参阅下面的@user315052 的答案,以使用如上所述的固定长度数组执行此操作。

【讨论】:

  • @user315052:啊,谢谢——我错过了。当我回答这个问题时,这是一堆未格式化且不完整的代码,我做了一个错误的假设。
【解决方案2】:

您将输入存储到单个变量a 中,每次读取更多输入时都会覆盖该变量。您应该存储每个输入,以便您的程序知道提供的所有输入,而不仅仅是提供的最后一个输入。

数组是一组连续排列的相同类型的变量,通过单一名称和索引访问。

int arr[10];

在此示例中,arr 构成 10 个连续的 ints。使用arr[0] 访问数组中的第一个int,使用arr[9] 访问最后一个。要将您的输入输入到数组中,您可以将a 存储到arr 的正确索引中。您可以通过计算用户到目前为止输入的数字来维护正确的索引。该计数将用作输入数组的索引。不允许用户超出声明中定义的数组边界,否则当您尝试存储超出与数组关联的最后一个位置的数据时,您将调用未定义的行为(发生这种情况时,称为缓冲区溢出)。

在将输入读入数组后,您可以将数组传递给冒泡排序函数。

假设您有这样的输入例程:

#define MAX_ARR 10
int a;
int entered = 0;
int arr[MAX_ARR];
while (entered < MAX_ARR) {
    if (scanf("%d", &a) != 1) break;
    if (a == -1) break;
    arr[entered] = a;
    ++entered;
}
if (entered == MAX_ARR) {
    printf("No more room in the array (max is %d)\n", MAX_ARR);
}

我们检查了scanf 已经返回了预期的返回值。我们已经根据停止值检查了输入,并确保用户输入的数据不能超过数组可以容纳的数据。

输入到数组中的元素数量为entered。因此,要遍历数组,循环看起来像这样:

int i;
for (i = 0; i < entered; ++i) {
    printf("arr[%d] = %d\n", i, arr[i]);
}

冒泡排序的一个非常简单的版本就是不断循环遍历数组,直到您不再需要进行任何交换。每当两个连续的元素未按所需顺序时,您就可以交换。对于升序情况:

int j, swaps, unsorted = entered;
do {
    swaps = 0;
    for (j = 1; j < unsorted; ++j) {
        /* ... if arr[j-1] and arr[j] need to swap then:
                   swap them, and
                   increment swaps ... */
    }
} while (swaps > 0);

您知道数组最后一个位置的元素将在一次完整的冒泡循环结束时处于其排序位置,因此可以在每次完整遍历后减少unsorted 的数量。

【讨论】:

    【解决方案3】:

    对于第一个版本有一个固定大小的数组说

    int myarray[100];
    //Accept the integers 
    
    index=0;
    do {
        scanf("%d", &myarray[index]);
        index++;
    }    while(myarray[index-1]!= -1);
    

    现在你有了数组和总数 元素 - (index-1)

    您可以对数组应用排序算法。

    【讨论】:

    • 好的,这真的很有帮助,但我似乎无法用“-1”来停止输入。有什么想法吗?
    • a 更改为myArray[index-1],因为这是您现在输入的内容。
    • @chris 谢谢克里斯..我在答案中添加了这一点。
    • 我几乎让它工作了,但它在编译后崩溃了。原帖中的最新代码,有什么想法吗?
    【解决方案4】:
    #include <stdio.h>
    #include <stdlib.h>
    
    typedef enum _order {
        Ascending=1, Descending
    } order;
    
    void swap(int *x, int *y){
        int wk;
        wk=*x;*x=*y;*y=wk;
    }
    
    int needSwap(int x, int y, order dir){
        if(dir == Ascending)
            return x > y;
        if(dir == Descending)
            return x < y;
        return 0;
    }
    
    void bubbleSort(int *array, int top, int end, order dir){
        int i, j, swaped;
        for(i = top; i < end; ++i){
            swaped = 0;
            for(j = top + 1; j <= end - i; ++j)
                if(needSwap(array[j-1], array[j], dir)){
                    swap(&array[j-1], &array[j]);
                    swaped = 1;
                }
            if(swaped == 0)break;
        }
    }
    
    int main(){
        int myarray[100], index, order;
        index=0;
        printf("Enter your numbers. Write -1 to stop. \n");
        do{
            scanf("%d", &myarray[index++]);
        }while(myarray[index-1] != -1 && index < 100);
        --index;//Correction to point to the final value
        printf("Enter 1 if you want them to be in ascending order.\n"
               "Enter 2 if you want descending order\n");
        scanf("%d",&order);
        bubbleSort(myarray, 0, index-1, order);
        {//result print
            int i;
            for(i=0;i<index;++i)
                printf("%d ", myarray[i]);
            printf("\n");
        }
        system("PAUSE");
        return 0;
    }
    

    【讨论】:

    • @user315052:外循环也是如此。
    • 冒泡排序是“比较每对相邻的项目,如果它们的顺序错误则交换它们”。
    • @user315052 : 很高兴你能理解。
    • @BLUEPIXY:我很高兴提问者得到了正确的答案,问候
    • 注意:与swap标志的存在与否无关的是是否优化。
    猜你喜欢
    • 1970-01-01
    • 2012-10-20
    • 2018-03-29
    • 2019-01-19
    • 2016-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-05
    相关资源
    最近更新 更多