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

来源:互联网 发布:go系列软件 编辑:程序博客网 时间:2024/06/15 17:20

目录

    • 目录
    • 题目
    • 主函数main
    • sort函数

题目

  • 将数组中等于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