gpt4 book ai didi

c++ - 快速排序问题 (C++)

转载 作者:搜寻专家 更新时间:2023-10-31 01:52:59 28 4
gpt4 key购买 nike

<分区>

使用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;
}

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com