2011-05-25 141 views
1

我正在使用Turbo C,並且對我的代碼進行了一些查詢。我只是困惑...程序首先要求一個數字列表(你不應該輸入超過20)。當用戶鍵入數字時,它們被放置在數組list[]中。一旦用戶通過鍵入0 *(不在列表中)*終止列表,程序將調用sort()函數,該函數對列表中的值進行排序。在最後一部分,其中有/*I AM NOW CONFUSED WITH THIS PART*/的評論,是我需要你的幫助的部分...請幫助我。排序數組問題

enter image description here

 File Edit Run Compile Project Options Debug Break/watch 
    ╒════════════════════════════════════ Edit ════════════════════════════════════╕ 
    │  Line 1  Col 43 Insert Indent Tab Fill Unindent * C:NONAME.C   │ 
    │                    │ 
    │ #define MAXSIZE 20       /* size of buffter */   │ 
    │ void sort(int[], int);      /* prototype */    | 
    │                    | 
    │ main()                  | 
    │ {                   | 
    │  static int list[MAXSIZE];     /* buffer for numbers */  | 
    │  int size = 0;        /* size 0 before input */  | 
    │  int dex;         /* index of array */   | 
    │  do          /* get list of numbers */  | 
    │  {                  | 
    │   printf("Type number: ");            | 
    │   scanf("%d", &list[size]);           | 
    │  }                  | 
    │  while(list[size++] != 0);     /* exit loop on 0 */   | 
    │                    | 
    │  sort(list,--size);      /* sort nubmers */    | 
    │  for(dex=0; dex<size; dex++)    /* print sorted list */  | 
    │   printf("%d\n", list[dex]);           | 
    │                    | 
    │  getche();                | 
    │ }                   | 
    │                    | 
    │ void sort(int list[], int size)            | 
    │ {                   | 
    │  int out, in, temp;      /* I AM NOW CONFUSED */  | 
    │                    | 
    │  for(out=0; out<size-1; out++)    /* IN THIS PART! */   | 
    │   for(in=out; in<size; in++)           | 
    │    if(list[out] > list[in])          | 
    │    {                | 
    │     temp=list[in];            | 
    |     list[in]=list[out];           | 
    │     list[out]=temp;            | 
    │    }                | 
    │ }                   | 
    │                    | 
    │                    | 
    ├─────────────────────────────────── Watch ────────────────────────────────────┤ 
    │                    │ 
    └──────────────────────────────────────────────────────────────────────────────┘ 
    F1-Help F5-Zoom F6-Switch F7-Trace F8-Step F9-Make F10-Menu NUM 
+2

請告訴我什麼是錯的... – aer 2011-05-25 03:53:42

+0

這只是看起來像一個[冒泡排序(http://en.wikipedia.org/wiki/Bubble_sort),雖然它沒有做正確的交換。 – chrisaycock 2011-05-25 03:55:06

+1

什麼問題? – bdares 2011-05-25 03:57:08

回答

2

這只是意味着數組元素進行排序的代碼,但它永遠不會因爲目前的形式工作:

temp=list[in]; 
list[out]=temp; 

將覆蓋list[out]list[in]而沒有保存list[out]原始內容。

交換兩個變量的最佳方式是這樣的:

temp = array[index1]; 
array[index1] = array[index2]; 
array[index2] = temp; 

而且,請你相信什麼神的愛,不要做this :-)

所以,如果你的問題是如何排序數據,那麼下面的僞代碼應該有所幫助。我會提供C代碼,但是,如果這是家庭作業,你應該自己做一些工作a

def sort (arr[], sz): 
    swapped = true      # Force loop entry. 
    while swapped:      # Loop until a pass had no swaps. 
     swapped = false 
     for idx goes from 1 to sz-1:  # For all but the first element. 
      if arr[idx-1] > arr[idx]: # If order is wrong. 
       swapped = true   # More passes will be needed. 
       temp = arr[idx-1]  # Swap 
       arr[idx-1] = arr[idx] # the 
       arr[idx] = temp   #  elements. 

這是一個氣泡排序變化,一旦列表排序(好,一次傳遞後沒有交換)就退出。無論如何,一些天真的變體只會持續大約n2次。


一個如果您想在一個評論,它的作業指示,我很樂意提供的C代碼。請注意(如果您打算對我說謊),您的教育工作者幾乎肯定能夠看到該代碼,您可能會在此情況下失敗(或因公然抄襲而被開除)。


而且,由於你說這不是功課,這裏說明一個完整的C程序:

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

#define FALSE (1==0) 
#define TRUE (1==1) 

static void sort (int arr[], int sz) { 
    int idx, temp, swapped; 

    swapped = TRUE;      // Force loop entry. 
    while (swapped) {      // Loop until a pass had no swaps. 
     swapped = FALSE; 
     for (idx = 1; idx < sz; idx++) { // For all but the first element. 
      if (arr[idx-1] > arr[idx]) { // If order is wrong. 
       swapped = TRUE;   // More passes will be needed. 
       temp = arr[idx-1];   // Swap 
       arr[idx-1] = arr[idx];  // the 
       arr[idx] = temp;   //  elements. 
      } 
     } 
    } 
} 

 

int main (int argc, char *argv[]) { 
    int sz, i, *vals; 

    sz = argc - 1; 
    if (sz < 1) 
     return 0; 
    if ((vals = malloc (sz * sizeof (int))) == NULL) { 
     printf ("ERROR: Cannot allocate memory.\n"); 
     return 1; 
    } 

    for (i = 0; i < sz; i++) 
     vals[i] = atoi (argv[i+1]); 

    printf ("Numbers before:"); 
    for (i = 0; i < sz; i++) 
     printf (" %d", vals[i]); 
    printf ("\n"); 

    sort (vals, sz); 

    printf ("Numbers after :"); 
    for (i = 0; i < sz; i++) 
     printf (" %d", vals[i]); 
    printf ("\n"); 

    free (vals); 
    return 0; 
} 

與運行此:

$ ./testprog 3 1 4 1 5 9 2 6 5 3 5 8 9 

給出y ou輸出:

Numbers before: 3 1 4 1 5 9 2 6 5 3 5 8 9 
Numbers after : 1 1 2 3 3 4 5 5 5 6 8 9 9 
+0

@paxdiablo不,它不是作業...我們還沒有達到開學日期... – aer 2011-05-25 05:30:20

+0

@paxdiablo ...我修改了我的代碼,它確實有效。但我還有一些問題。在'for(out = 0; out aer 2011-05-26 08:28:33

+0

@paxdiable ...我把這個'-1',因爲我認爲,它應該排除用戶輸入0來終止程序...但我已經在函數調用'sort(list, - size);'中減小了'size'的大小。 – aer 2011-05-26 08:35:43

1

sort()最內環路的值交換是不完全的。它永遠不會爲list[in]分配任何東西。

0

我相信以下是你正在做的事情。基本上,你試圖在每個內部循環迭代中找到最小元素。例如,如果從數組[5,4,3,2,1]開始,在第一次內循環迭代之後,數組看起來像下面那樣:

[5,4,3,2, 1]:在經過= 0

[4,5,3,2,1]:在後= 1

[3,5,4,2,1]:在後= 2

[2,5,4,3,1]:後= 3

[1,5,4,3,2]:在後= 4

現在1是在開始。最終,數組將按[1,2,3,4,5]排序。

void sort(int list[], int size) { 
    int out, in, temp;  
    for(out=0; out<size; out++) {  | 
     for(in=out; in<size; in++)           
      if(list[out] > list[in])           
      {                
       tmp = list[out] 
       list[out]=list[in]; 
       list[in] = tmp                       
      }  
    }               
} 
+0

最後輸入的0如何終止程序? – aer 2011-05-25 05:38:35

+0

@aerohn你可以調用sort(list,size - 1)進行排序,這將解決你的問題。 – CEGRD 2011-05-31 09:58:59