2

使用QUICKSORT,对包含偶数的整数数组进行升序排序,奇数降序排序。

例如:输入 int a[8]={4,6,1,2,5,3,8,7} => 输出为 {2,4,6,8,7,5,3,1}。


我认为 QSort 函数会让我看起来像这样 B={4,6,2,8,1,3,7,5} 我会将 B 数组拆分为两个数组 C 和 D。


C 数组包含偶数 {4,6,2,8},我将使用 QuickSort 对 C 数组进行排序,如下所示 {2,4,6,8}


D数组包含uven编号{5,3,1,7},我将使用QuickSort对D数组进行排序{7,5,3,1}之后我将加上C和D。最后我的预期结果是{2,4,6,8,7,5,3,1} 这是我的代码 :(!非常感谢!

    void Input(int a[], int n)
    {
        for(int i = 0; i<n;i++)
        {
            cout<<"a["<<i<<"]: ";
                cin>>a[i];
        }
    }
    void Display(int a[],int n)
    {
        for(int i = 0;i < n; i++)
        {
            cout<<a[i]<<" ";
        }
        cout<<endl;
    }
    void Swap(int &a, int &b)
    {
        int temp = a;
        a=b;
        b=temp;
    }
    void QuickSort(int a[],int Left ,int Right)
    {
        int i, j, x;
        x = a[(Left + Right)/2];
        i = Left;j = Right;
        do
        {
            while( a[i]<x) i++;
            while(a[j]>x) j--;
            if(i<=j)
            {
                Swap(a[i],a[j]);
                    i++; j--;
            }
        }while (i<=j);
        if(i<Right) QuickSort(a,i,Right);
        if(Left<j) QuickSort(a,Left,j);

    }
   //after sort the array with function QuickSort, i was suggested to use 1 more       QuickSort 
   // to move evennumber to the top of the array
    void QSort(int a[],int Left,int Right)
    {
        int i, j, x;
        x = a[(Left + Right)/2];
        i = Left;j = Right;

        {
            while(a[i]%2==0 && a[i]<x ) i++;
            while(a[j]%2==1 && a[j]>x) j--;
            if(i<=j)
            {
                Swap(a[i],a[j]);
                    i++; j--;
            }
        }while (i<=j);
        for (i = 0; i<r;i++)
        {

        }
        if(i<Right) QSort(a,i,Right);
        if(Left<j) QSort(a,Left,j);
    }


    int main()
    {
          //n is numbers of integer array
        int a[Max],n;
            cout<<"Insert numbers of array: ";
            cin>>n;
            Input(a,n);
            cout<<"Array:\n";
            Display(a,n);
            cout<<endl;

            cout<<"Array after arrange: \n";
            QuickSort(a,0,n-1);
            Display(a,n);
            cout<<endl;

            cout<<"move even number to the top:\n";
            QSort(a,0,n-1);
            Display(a,n);

        return 0;
    }
4

1 回答 1

3

那么,数字 1 到 10 应该排序为{2,4,6,8,10,9,7,5,3,1}?

无需查看您的代码,我可以告诉您,您不需要两个快速排序函数。

让偶数比奇数少。相同奇偶校验的数字按指定进行比较。

于 2012-08-03T18:14:32.740 回答