如何正确使用选择排序算法对列表进行排序

How to use selection sort algorithm correctly to sort a list?

本文关键字:排序 列表 算法 选择 何正确      更新时间:2023-10-16

我不能让这个工作,似乎无论我做什么,它从来没有正确排序。

我正在尝试根据点数降序排序。

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

应该是这样的…

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

如果仅中间列用于排序,即用于排序记录的键,则不需要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;
        }
  }
}

它将按你想要的"降序"排序你的所有记录

如何将数据存储到std::vector中然后对其排序

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

尽量使用vector,它们已经为性能和更好的内存使用进行了大量优化