2014-11-23 69 views
1

如果我有一個int[3]陣列像這樣:c將整型數組排序

score_list[3] = [ 1, 2, 0] 

當陣列中的每個位置對應於一個特定的文件編號:

score_list[0] = D1 
score_list[1] = D2 
score_list[2] = D3 

什麼將是最簡單的方法按降序對數組進行排序,跟蹤每個移動的位置int

其中(排序後):

score_list[3] = [ 2, 1, 0] 

而且

score_list[0] = D2 
score_list[1] = D1 
score_list[2] = D3 

我只需要按降序排列打印,實際上沒有重新排列int數組,因此:

for (int i=0; i<3; i++) 
{ 
    if (score_list[0] > score_list[1] && score_list[2]) 
     printf("D%d-%d",i, score_list[0]); 
    if (score_list[1] > score_list[0] && score_list[2]) 
     printf("D%d-%d", i, score_list[1]); 
    if (score_list[2] > score_list[0] && score_list[1]) 
     printf("D%d-%d", i, score_list[2]); 
} 

會先打印次數最多的話,我會比較最後2,我只是覺得這需要太長時間,並且必須有更高效的方式

+3

請描述你嘗試過什麼。 – davidc 2014-11-23 23:29:14

+0

我不明白你在數組中存儲什麼?值或字符串?或者兩者如何相關? – 2014-11-23 23:30:38

+0

這是一個int數組,根據 – davidc 2014-11-23 23:33:14

回答

1

您可以使用marker (interface) design pattern
通過每次得到的最大時間保持訪問索引的記錄數組中,讓我定義的解決方案結構第一,然後我會穿行:

  1. 做的同樣大小的新數組score_list,讓我們調用數組
  2. 在for循環中,你會做另一個循環來檢查最高分,並在同一時間檢查,看是否標記陣列中的最高得分的位置是0

樣品運行:
i=0
環路上score_list,並找到標記== 0的最高分,它打印,然後把標記爲得分= 1
i=1
你會做相同的,但現在有一個位置從列表中

在這裏,你是一個示例代碼如何做到這一點除外:
需要注意的是:這個代碼是不是一個可運行的一個(它沒有優化過爲O(n^2)),我只是爲了解釋的目的而寫的。

int max = -1; 
int doc = -1; 
int marker[3] = {0, 0, 0}; 
for (i=0; i<3; i++) 
{ 
    max = -1; 
    for (j=0; j<3; j++) 
    { 
     // skip this location if it is already printed 
     if (marker[j] == 1) 
      continue; 

     if (score_list[j] > max) 
     { 
      doc = j; 
      max = score_list[j]; 
     } 
    } 

    // this doc will not appear again in the inner for loop (j-loop) 
    marker[doc] = 1; 

    // print the document with the score 
    printf("D%d-%d",doc, max); 
}