2013-03-29 58 views
2

我無法得到這個工作,似乎無論我做什麼,它從來沒有正確排序。如何正確使用選擇排序算法對列表進行排序?

我想根據點數降序排序。

Bryan_Bickell   2 5 +2 

Brandon_Bolig   0 3  0 

Dave_Bolland   4 2 -1 

Sheldon_Brookbank  0 4 -1 

Daniel_Carcillo  0 1 +3 

中間一列是點數。

我正在使用4個數組來存儲所有這些值,我將如何正確利用數組選擇排序以正確的方式進行排序?

我曾嘗試下面的所有答案,但沒有人似乎工作,這是我迄今爲止

void sortArrays(string playerNames[], int goals[], int assists[], int rating[], int numPlayers) 
{ 
int temp, imin; 
int points[numPlayers]; 

for(int j = 0; j < numPlayers; j++) 
    { 
     points[j] = goals[j] + assists[j]; 
    } 

    imin = points[0]; 

for(int i = 0; i < numPlayers; i++) 
{ 
    if (points[i] < imin) 
    { 
     imin = points[i]; 
    } 
} 

for(int j = 1; j < numPlayers; j++) 
{ 
    if (points[j] > imin) 
    { 
     temp = points[j]; 
      points[j] = points[j-1]; 
       points[j-1] = temp; 
    } 
} 
} 
+1

我猜你需要修改你個優化上墨...選擇排序處理在每次迭代中尋找最小值...您沒有設置任何最小值... pls參考http://stackoverflow.com/questions/8362640/java-selection-sort-algorithm?rq = 1 –

+2

你的「交換」是越野車;注意變量'temp'從不設置。此外,你的代碼看起來像是冒泡排序的一部分,而不是選擇排序。 – comingstorm

+0

這裏有'std :: swap';) - >'使用std :: swap;'''swap(points [i],points [i + 1]);' – leemes

回答

3

它應該像這樣...

void selsort(int *a,int size) 
{ 
    int i,j,imin,temp; 
    //cnt++; 
    for(j=0;j<size;j++) 
    { 
     //cnt+=2; 
     imin=j; 
     for(i=j+1;i<size;i++) 
     { 
      //cnt+=2; 
      if(a[i]<a[imin]) 
      { 
      //cnt++; 
      imin=i; 
      } 
     } 

     if(imin!=j) 
     { 
      //cnt+=3; 
      temp=a[j]; 
      a[j]=a[imin]; 
      a[imin]=temp; 
     } 
    } 
} 
+0

a將成爲您所需的陣列 –

+0

不應該是j <大小-1?否則最後的i = j + 1會超出數組邊界 – Valentin

+0

調用是這樣的...對於(i = 0; i

1

你不如果僅使用中間列進行排序,即用於排序記錄的鍵,則不需要4個數組來存儲這些記錄。根據我的理解,你試圖根據選擇排序的點數來排序這些人的記錄。代碼應該如下所示:假設records是你的記錄

void selectionSort(RECORD records[], int n) { 
    int i, j, minIndex, tmp;  
    for (i = 0; i < n - 1; i++) { 
     maxIndex = i; 
     for (j = i + 1; j < n; j++) //find the current max 
     { 
       if (records[j].point > records[minIndex].point) 
       { 
        //assume point is the number of point, middle column 
        minIndex = j; 
       } 
     } 

     //put current max point record at correct position 
     if (minIndex != i) { 
       tmp = records[i]; 
       records[i] = records[minIndex]; 
       records[minIndex] = tmp; 
     } 
    } 
} 

它將「降序」中,只要你想

+0

注意。如果使用'int records []'','.point'位是不正確的......我假定這是來自另一個使用struct的草稿? – Useless

+0

@不用說是的,我很粗心,我的意思是一系列的結構。謝謝! – taocp

0

所有的記錄進行排序陣列如何存儲中的數據到一個std ::向量在排序

int compare(int a, int b){ 
return (a>b); 
} 

void sort(std::vector<int> &data){ 
std::sort(data.begin(), data.end(), compare); 
} 

嘗試使用矢量儘可能多的可能,他們已經沉重的性能和更好的內存使用情況

相關問題