所以我试着做一种类似泡泡的类型。不是泡沫类型,因为我不想交换我遇到的每一个值。我只想找到每个索引的最小值,并将其排序。比如在arrayVal3中,5,2。
而不是将值3替换为2,然后将5替换为3。我希望找到整个数组中最小的数目,并将其放置在arrayVal,然后移动到arrayVal1。
我不知道该怎么做,所以有点卡住了。(我在库上取出了<>,这样你就可以看到我使用的是哪个库)。
#include iostream
#include cmath
#include ctime
using namespace std;
int main()
{
const int STARTLOOP = 0;
const int MAXLOOP = 5;
const int MINRANGE = 1;
const int MAXRANGE = 10;
//int temp = 0;
int smallestVal = 0;
int arrayVal[MAXLOOP];
srand(time(0));
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
arrayVal[i] = (rand() % MAXRANGE) + MINRANGE;
}
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
cout << arrayVal[i] << endl;
}
cout << "Before the sort" << endl;
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
for (int j = i; j < MAXLOOP; j++)
{
if (arrayVal[j] < arrayVal[i])
{
arrayVal[i] = smallestVal;
}
}
}
for (int i = STARTLOOP; i < MAXLOOP; i++)
{
cout << arrayVal[i] << endl;
}
cout << "After the sort" << endl;
return 0;我还意识到我没有使用函数,我只是编写了代码,因为我正在试图解决这个问题。提前谢谢你。
发布于 2017-11-17 00:46:58
您永远不会将smallestVal设置为数组中的任何内容。你不需要嵌套循环。只需遍历数组一次,将每个值与smallestVal进行比较。如果它较小,则将smallestVal设置为该值。您还应该有一个变量,该变量保存最小值的索引,同时更新该索引。
最后,用最小的元素交换第一个元素。
int smallestVal = arrayVal[STARTLOOP];
int smallestIndex = STARTLOOP;
for (int i = STARTLOOP + 1; i < MAXLOOP; i++) {
if (arrayVal[i] < smallestVal) {
smallestVal = arrayVal[i];
smallestIndex = i;
}
}
if (smallestIndex != STARTLOOP) {
// swap it with the first element
int temp = arrayVal[STARTLOOP];
arrayVal[STARTLOOP] = smallestVal;
arrayVal[smallestIndex] = temp;
}然后,您可以增加STARTLOOP并重复此操作。
发布于 2017-11-17 00:54:26
您想要实现的是某种修改的插入排序。请查看此实现:
void sort(int values[], int n)
{
for (int i = 0; i < n; ++i)
{
int min = i;
for ( int j = i ; j < n ; j++)
{
if (values[j]<values[min]) min =j;
}
while(values[min-1]>values[min])
{
if(min==0)
break;
if(values[min-1]!=values[min])
swap (values+min-1,values+min);
min--;
}
}
return;
}这个函数的作用是每次从索引i开始搜索数组中最小的元素,当它找到这个元素时,它会继续交换数组中的所有前面的元素,直到到达一个较小的元素为止。
https://stackoverflow.com/questions/47341488
复制相似问题