将数组中等于n的元素移到数组的最前面,尽量减少数组元素的移动次数和额外存储

8 篇文章 0 订阅
7 篇文章 0 订阅

目录

题目

  • 将数组中等于n的元素移到数组的最前面,尽量减少数组元素的移动次数和额外存储,比如数组为[2,4,5,2,5,8,11,44,29,16,2],n=2, 则输出数组[2,2,2,4,5,5,8,11,44,29,16],其中4,5,5,8,11,44,29,16的顺序不指定,不必维持在原数组中的顺序。

主函数main

int main(int argc, char const *argv[])
{
    int n,m,i=0;
    const int length = 4;

    //cout << "Input an number...";
    //cout << "Input length..." ;
    //cout << "Input an array ..." << endl;

    //cin >> length;错误
    //cin >> arr;错误
    int arr[length] = {0};//内置数组的长度在编译的时候就必须知道,当length=4时,其实用sizeof(int)或sizeof(length)的结果是一样的,而且在编译的时候就已经知道大小了。
    //int arr[length];正确
    while(i<length)
    {
        cin>>m;
        arr[i++]=m;
    }
    for (auto c : arr)
        cout << c;
    cout << endl;

    cout<<"Input n = ";
    cin>>n;
    sort(arr, n, length);
    return 0;
}

sort函数

void sort(int a[], int n, int length){
    int left = 0;int right = length -1;
    while(a[left] == n) ++left;
    while(left < right)
    {
        if (a[right] != n)
        {
            --right;
        }
        else
        {
            swap(a[left], a[right]);
            --right;
            ++left;
            while(a[left] == n) ++left;
        }
    }
    for (int c =0;c<length;++c)
        cout << a[c];
    cout << endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值