简单排序功能不起作用。建议?
Simple Sort function not working. Suggestions?
void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; k++)
{
for (int j = k; j>0 && students_id[j]<students_id[j-1]; j--)
{
int place_holder = indices[j];
indices[j] = indices [j-1];
indices[j-1] = place_holder;
}
}
}
嗨,
我必须创建一个能够对整数数组进行排序的函数,不是通过更改和重新排列其内容,而是通过更改另一个整数数组(称为索引)中的整数顺序。所以,我会有一个包含一系列 id 的数组,例如:让我们称这个 id" [#] 表示索引 [0]10001 12001 212334 [3]14332 [4]999999 [5]10111
有一个对应的数组,整数值 [#] 是索引让我们调用这个 arr [0]0 11 [2}2 [3]3 [4]4 [5]5 这样它们就对应于我们的索引另一个数组。
现在,我们必须改变 "arr" 的顺序,使元素的顺序与数组 id 中索引的顺序相对应。请注意,数组 ID 不会以任何方式更改。
因此,我们可以通过使用 for 循环、arr 的值和数组 id,按升序将 ids 打印到控制台。
拜托,如果您能够在不创建非常复杂的函数的情况下提供建议,我将不胜感激。我只想更改我创建的现有功能,使其正常工作。
到目前为止,这是我的函数的输出:
如有任何意见或建议,我们将不胜感激。
索引students_id数组时,不要使用j和j-1,而是使用-> indices[j]和indices[j-1]。因此,您将使用 students_id 数组更改索引数组中的顺序以获取要比较的值。
for (int j = k; j>0 && students_id[indices[j]]<students_id[indices[j-1]]; j--)
另外我会把循环改成
void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; ++k)
{
for (int j = 0; j<k; ++j)
{
if(students_id[indices[j]]>students_id[indices[j+1]]) {
int place_holder = indices[j];
indices[j] = indices [j+1];
indices[j+1] = place_holder;
}
}
}
}
我想到了最简单的冒泡排序。
void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; k++)
{
for (int j = k; j>0 && students_id[j]<students_id[j-1]; j--)
{
int place_holder = indices[j];
indices[j] = indices [j-1];
indices[j-1] = place_holder;
}
}
}
嗨,
我必须创建一个能够对整数数组进行排序的函数,不是通过更改和重新排列其内容,而是通过更改另一个整数数组(称为索引)中的整数顺序。所以,我会有一个包含一系列 id 的数组,例如:让我们称这个 id" [#] 表示索引 [0]10001 12001 212334 [3]14332 [4]999999 [5]10111 有一个对应的数组,整数值 [#] 是索引让我们调用这个 arr [0]0 11 [2}2 [3]3 [4]4 [5]5 这样它们就对应于我们的索引另一个数组。 现在,我们必须改变 "arr" 的顺序,使元素的顺序与数组 id 中索引的顺序相对应。请注意,数组 ID 不会以任何方式更改。 因此,我们可以通过使用 for 循环、arr 的值和数组 id,按升序将 ids 打印到控制台。
拜托,如果您能够在不创建非常复杂的函数的情况下提供建议,我将不胜感激。我只想更改我创建的现有功能,使其正常工作。
到目前为止,这是我的函数的输出:
如有任何意见或建议,我们将不胜感激。
索引students_id数组时,不要使用j和j-1,而是使用-> indices[j]和indices[j-1]。因此,您将使用 students_id 数组更改索引数组中的顺序以获取要比较的值。
for (int j = k; j>0 && students_id[indices[j]]<students_id[indices[j-1]]; j--)
另外我会把循环改成
void sort_records_by_id (int []indices, int []students_id )
{
for (int k = 1; k<students_id.length; ++k)
{
for (int j = 0; j<k; ++j)
{
if(students_id[indices[j]]>students_id[indices[j+1]]) {
int place_holder = indices[j];
indices[j] = indices [j+1];
indices[j+1] = place_holder;
}
}
}
}
我想到了最简单的冒泡排序。