C++ 如何让此选择搜索工作?
我正在尝试按降序对数组中的十个值进行排序,但似乎无法正确排序 我已经试着在我的书中复制了两次代码,我甚至从youtube上复制了一段代码,但仍然不起作用。有人请帮帮我!我什么都试过了,都吓坏我了C++ 如何让此选择搜索工作?,c++,C++,我正在尝试按降序对数组中的十个值进行排序,但似乎无法正确排序 我已经试着在我的书中复制了两次代码,我甚至从youtube上复制了一段代码,但仍然不起作用。有人请帮帮我!我什么都试过了,都吓坏我了 void selectionSort(int list[], int size) { //Display variables int minIndex, minValue, num; //Calculate the array in descending order for(int i
void selectionSort(int list[], int size)
{
//Display variables
int minIndex, minValue, num;
//Calculate the array in descending order
for(int index = 0; index < size; index++)
{
minValue = list[index];
minIndex = index;
for(int index2; index2 < size; index2++)
{
if(list[index2] < minValue)
{
minValue = list[index2];
minIndex = index2;
}
}
swap(list[index], list[minIndex]); //function call
}
//Display the array in descending order
cout<<"The scores in descending order are ";
for(int num = 0; num < size; num++)
{
cout<<list[num]<<" ";
}
cout<<endl;
void selectionSort(整数列表[],整数大小)
{
//显示变量
int minIndex,minValue,num;
//按降序计算数组
对于(int index=0;index
正如编译器所说,可以删除第一个num,或者不在for中重新定义它
当我运行程序时,算法不会对任何内容进行排序,它会显示相同的精确数组,没有任何更改
以及你在上述更正后的评论:
改变了,但我还是得到了同样的结果
一个可能的原因是您定义了自己的掉期,但定义没有这样做:
void swap(int a, int b)
{
int c = a;
a = b;
b = c;
}
而不是举例来说
void swap(int & a, int & b)
{
int c = a;
a = b;
b = c;
}
或者使用一个模板当然也许你的书中有一个打字错误-你没有为(int index2=index+1;index2index2
,更改了它,但我仍然得到了相同的结果。@KoolKassia可能是你定义了你自己的交换,实际上什么都不做?(我编辑了我的答案)问题可能是您的函数不正确,因此如果您给它一个升序数组(在修复索引错误之后),您将看不到任何差异。
#include <iostream>
using namespace std;
void selectionSort(int list[], int size)
{
//Display variables
int minIndex, minValue, num;
//Calculate the array in descending order
for(int index = 0; index < size; index++)
{
minValue = list[index];
minIndex = index;
for(int index2 = index+1; index2 < size; index2++)
{
if(list[index2] < minValue)
{
minValue = list[index2];
minIndex = index2;
}
}
swap(list[index], list[minIndex]); //function call
}
//Display the array in descending order
cout<<"The scores in descending order are ";
for(int num = 0; num < size; num++)
{
cout<<list[num]<<" ";
}
cout<<endl;
}
int main()
{
int v[] = { 1,8,6,9,0,2,3};
selectionSort(v, (int) (sizeof(v)/sizeof(int)));
return 0;
}
pi@raspberrypi:/tmp $ g++ -pedantic -Wall -Wextra c.cc
c.cc: In function ‘void selectionSort(int*, int)’:
c.cc:7:27: warning: unused variable ‘num’ [-Wunused-variable]
int minIndex, minValue, num;
^~~
pi@raspberrypi:/tmp $ ./a.out
The scores in descending order are 0 1 2 3 6 8 9
void swap(int a, int b)
{
int c = a;
a = b;
b = c;
}
void swap(int & a, int & b)
{
int c = a;
a = b;
b = c;
}