c++ - 通过向右移动对值数组进行排序

标签 c++ arrays function sorting

我必须创建一个方法来对值数组从最低值到最高值进行排序。这些函数的工作方式应该是它获取每个值,并尝试通过将每个较大的值向右移动来将它们按从左到右的升序排列。

我做了以下功能:

int findIndex(double *arr, double num, int length)
{

   for (int i = 0; i < length; i++)
   {
      if (arr[i] > num)
         return i;
     }
   return length - 1;
}

void placeOnIndex(double *arr, double num,int index, int length)
{

   if (length > 1 && arr[index] != num) 
   {
       for (int i = length - 1; i > 0; i--)
       {
            arr[i] = arr[i - 1];
       }

       arr[index] = num;
   }
}

void insertSort(double* arr, int length)
{
   for (int ix = 0; ix < length; ix++)
   {
       double num = arr[ix]; //Current value to put as far to the left as possible
       int index = findIndex(arr, num, ix+1);  //Locates index to put it
       placeOnIndex(arr, num, index, ix+1); //Uses the index to put in the right place
   }

}

void main()
{
   double arr[4] = {1,8,4,5};
   insertSort((arr), 4);
}

我的问题是这个数组的输出变成了: 1,1,5,8

显然它有时会覆盖我数组中的第二个元素。有时有效,有时无效。如果数组更长,则会覆盖更多值。

很抱歉,如果它看起来令人困惑,英语不是我的母语。

最佳答案

这一行

for (int i = length - 1; i > 0; i--)

使所有元素向右移动,而不仅仅是应该移动的元素。

你需要

for (int i = length - 1; i > index; i--)

关于c++ - 通过向右移动对值数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33310814/

相关文章:

sql - 如何使用 CTE (WITH) 在 postgresql 中插入多行

mysql - 如何在 MySQL 函数中引发错误

c++ - 代码复杂度指标和 ifdef

c++ - 将数组匹配分配给字符串

arrays - 在数组子对象上创建 Postgres JSONB 索引

java - 在Android中通过httpost发送字节数组

C程序: Strcmp

postgresql 错误 - 错误 : input is out of range

附加参数的 C++ 模板问题

c++ - 快速连续的 notify_all()s 不会解锁 condition_variable?