从数组中删除并移位

Deleting from an array and shifting

本文关键字:删除 数组      更新时间:2023-10-16

对于大小为5的数组,我试图在0和数组的当前最后一个元素之间找到一个随机位置。

(最后一个位置第一次是4,第二次是3,依此类推。)

删除该数组位置中的任何元素,将其上方的所有元素下移,使数组中没有空位。

我试图尽可能节省时间,所以我想避免将所述随机位置设置为0或类似的值。

所以,如果我的数组看起来像int n[] = {1,3,5,7,9};,而我的随机位置查找器选择了位置2,我如何将5(位置2)移到最后,并将所有内容下移,使我得到的数组看起来就像{1,3,7,9,5}

到目前为止,我有:

for (int j = 0; j < 5; j++)
    {
    printf ("before removal:n");
    printarray (array, 5);
    int randompos =  (   rand() % (5-j)   ); //selects random number from 0 to active last pos.
    /* ?????? */ = array[randompos]; // What position will hold my random position?
//Also, what goes in place of the 'deleted' element?
    insertion_sort (array, 5-j); //sort only the active elements
    printf ("after removal:n");
    printarray (array, 5);
    }

期望输出:

before removal:
1,3,5,7,9

(假设随机位置为阵列位置2,存储编号5)

after removal:
1,3,7,9,5

给定数组{1,3,5,7,9}pos = 2,可以执行以下操作:

int main()
{
    int pos = 2;
    int arr[] = {1, 3, 5, 7,9};
    int length =sizeof(arr)/sizeof(arr[0]);
    int val = arr[pos];
    for (int i = pos; i < length; i++){
        int j = i + 1;
        arr[i] = arr[j];
    }
    arr[length - 1] = val;
    return 0;
}
#include <iostream>
#include <algorithm>
#include <random>
int main() {
  int n[] = {1, 3, 5, 7, 9};
  std::size_t n_size = sizeof(n) / sizeof(int);
  std::default_random_engine generator;  
  for(std::size_t i(0), sz(n_size); i < sz; ++i) {
    std::cout << "before removal:" << std::endl;
    std::cout << "  ";
    for(std::size_t j(0); j < n_size; ++j) std::cout << n[j] << " ";
    std::cout << std::endl;
    --n_size;
    std::uniform_int_distribution<int> distribution(0, n_size);
    std::size_t idx = distribution(generator);
    std::cout << "  Removing index: " << idx << std::endl;
    std::swap(n[idx], n[n_size]);
    std::sort(std::begin(n), std::begin(n) + n_size); // use your sorting here
    std::cout << "after removal:" << std::endl;
    std::cout << "  ";
    for(std::size_t j(0); j < n_size; ++j) std::cout << n[j] << " ";
    std::cout << "n" << std::endl; 
  } 
}

现场演示