简体   繁体   中英

function trouble about find largest in array

write a program that enter a series of integer(stores in array),then sorts the integer by calling the function selection_sort. When given an array with n elements, selection_sort must do the following: 1.search the array to find the largest,then move it to the last position. 2.call itself recursively to sort the first n-1 elements of the array.

following is my code i think the code is errors everywhere i hope some master can help me

#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;
}

You have to compare. BUt you are assigned..

change this if (a[i] = '\\n') { break; } if (a[i] = '\\n') { break; } to if (a[i] == '\\n') { break; } if (a[i] == '\\n') { break; } .

You should change follows in your code.

1) change your function call.. 2) declare count and i in function.. 3) for taking values in to array,follow other method..

Try yourself...

Here is the complete code.Basically there are many syntax and logical error in your code. Consider this as refer and compare with your original source.

 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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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