繁体   English   中英

查找数组中最大的函数的麻烦

[英]function trouble about find largest in array

编写一个输入一系列整数(存储在数组中)的程序,然后通过调用函数selection_sort对整数进行排序。 当给定一个包含n个元素的数组时,selection_sort必须执行以下操作:1.搜索数组以找到最大的数组,然后将其移到最后一个位置。 2.递归调用自身以对数组的前n-1个元素进行排序。

以下是我的代码,我认为代码到处都是错误,希望一些高手可以帮助我

#include <stdio.h>

int selection_sort(int a[])//this function have error that "i"and"count"is undeclared
{
   int max = 0;
   for (i = 1; i <= count; i++)// continuous compare to final
   {
      if (a[i] > max)
      {
         max=a[i];
      }
   }
   a[count] = a[i]; //put the max to last position 
   count--;
}

int main(void)
{
   int a[100] = { 0 },i=0,count=0;
   while (1)
   {
      scanf("%d",&a[i]);
      if (a[i] = '\n') { break; }//this line have error because '\n' not "int" so when i "enter" it would not break 

      i++;   
      count++;   //counting how many integer i scanf
   }

   selection_sort();//call this function (i don't know well about function so i don't known where to put is correct )

   return 0;
}

你必须比较。 BUT,您已分配..

if (a[i] = '\\n') { break; } if (a[i] = '\\n') { break; }if (a[i] == '\\n') { break; } if (a[i] == '\\n') { break; }

您应该在代码中更改以下内容。

1)更改函数调用。2)在函数中声明counti )将值放入数组,请遵循其他方法。

试试看...

这是完整的代码。基本上,您的代码中有很多语法和逻辑错误。 将此视为参考,并与原始来源进行比较。

 int selection_sort(int a[], int count){ 
    int max = 0, i =0;

    for (i = 0; i < count; i++){
        if (a[i] > max)
        {
            max=a[i];
        }
    }

    a[count] = max; 
    count--;

    return 0;
}

int main(void) { 

    int a[100] = { 0 },i=0,count=0;;
    printf ("Enter the total num\n");

    scanf("%d",&count);

    if ( ( count  ) >= (sizeof(a)/sizeof(a[0])) )
    return -1;

    while (i < count){
        scanf("%d",&a[i]);
        i++;   
    }

    selection_sort(a, count);

    printf ("\nmax:%d\n", a [count]);
    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM