如何正确使用选择排序算法对列表进行排序
How to use selection sort algorithm correctly to sort a list?
我不能让这个工作,似乎无论我做什么,它从来没有正确排序。
我正在尝试根据点数降序排序。
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,它们已经为性能和更好的内存使用进行了大量优化
相关文章:
- C 中的排序列表
- 使用霍尔分区方案的快速排序算法返回原始未排序列表
- 带有额外参数的排序列表以进行比较功能
- 算法,用于查找获取排序列表所需的最小移动元素到结束步骤
- 迭代排序列表并计算不同的数字
- 维护多集中数字的排序列表和另一个集合中的累积总和
- 超过合并 k 排序列表的时间限制(leetcode)
- 正在检查排序列表中是否有一个范围内的数字
- O(N) 查找,但在排序列表上使用 upper_bound 时进行 O(log(N)) 比较
- 如何在只更改一个元素的情况下在排序列表中进行快速排序
- 返回指向排序列表的指针;C++中的链表
- 除了显示平均,最高和最低温度之外,有没有办法打印出整个排序列表
- 整数排序列表..TMP
- c++排序:具有相同数组值的排序列表
- 复制C++中未排序列表的构造函数
- 如何将元素添加到排序列表中..?(C++)
- 三维对象的Z排序列表
- 在我的排序列表中插入项目时出现问题
- 将节点插入到不带头指针的排序列表中
- 使用"pop_front"从排序列表中删除元素会导致崩溃