设任意n个整数存放于数组A[1..n]中,试编写算法,将所有正数排在所有负数前面(要求:算法时间复杂度为O(n))。

注意数组的实际长度

#include <iostream>
using namespace std;

void sort(int A[],int n)
{
    int i=0;//数组的头下标
    int j,x;
    j=n-1;//数组的尾下标
    while (i<j)
    {
        while (i<j&&A[i]>0)i++;
        while (i<j&&A[j]<0)j--;
        if(i<j){x=A[i];A[i++]=A[j];A[j--]=x;}
    }
}


int main()
{
    int A[20]={0};
    int a,i=0;
    cout<<"请输入整型数组的元素,以0结束,不包括0"<<endl;
    while(a!=0)
    {
        cin>>a;
        A[i++]=a;
    }
    int n=i-1;//数组的实际长度

    cout<<"原数组为:";
    for(int j=0;j<n;j++)
        {cout<<A[j]<<" ";}

    cout<<endl;
    sort(A,n);//把数组中的整数排在负数前面

    cout<<"处理后的数组为:";
    for(int k=0;k<n;k++)
        {cout<<A[k]<<" ";}

    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42451835/article/details/83988490
今日推荐