2014-10-31 29 views
0

編寫一個程序,輸入一系列整數(在數組中存儲),然後通過調用函數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; 
} 
+0

您的代碼有語法錯誤。 'selection_sort'如何看見'count'?另外,你的邏輯'a [i] =='\ n')'有缺陷。 'a [i]'永遠不會是''n''。另外,您正在'selection_sort'中以起始索引'1'訪問數組。那需要'0'。 – 2014-10-31 04:34:23

+0

codeSmellHomework ++; //微笑 – Mawg 2014-11-14 13:32:33

回答

0

你要比較。你被分配了..

將此if (a[i] = '\n') { break; }更改爲if (a[i] == '\n') { break; }

您應該在代碼中更改以下內容。

1)改變你的函數調用.. 2)申報count和功能i .. 3)對數組取值,跟隨其他方法..

嘗試自己...

+0

int main(void) { \t int a [100] = {0},i = 0,count = 0; \t而(1) \t { \t \t的scanf( 「%d」,&a[i]); \t \t如果(A [1] == '\ n'){斷裂;} \t \t我++; \t \t計數++; \t} \t \t 的printf( 「%d」,A [2]); 返回0; } – bookgirl 2014-10-31 04:30:39

+0

我使用它來調試,但我t不會中斷 – bookgirl 2014-10-31 04:31:06

+0

行。我有班後,我會嘗試當我回來 – bookgirl 2014-10-31 04:45:53

0

以下是完整的代碼。基本上,代碼中有許多語法和邏輯錯誤。將此視爲引用並與您的原始來源進行比較。

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

感謝您的幫助,我會與我的後者比較,我應該去誇張。 – bookgirl 2014-10-31 04:55:04

+0

如果我也有問題,我仍然需要你的幫助。謝謝 – bookgirl 2014-10-31 04:55:58