Use QUICKSORT, sort the integer array contains even number in ascending order and uneven number in descending order.
ex: input int a[8]={4,6,1,2,5,3,8,7}
=>output is {2,4,6,8,7,5,3,1}.
I think the QSort function will give me look like this B={4,6,2,8,1,3,7,5} and i’ll split B array to two array is C and D.
C array contains even number {4,6,2,8} and i’ll use QuickSort to sort C array like this {2,4,6,8}
D array contains uven number {5,3,1,7} and i’ll use QuickSort to sort D array like this {7,5,3,1}
After that i’ll plus C and D. Finally my expected result is {2,4,6,8,7,5,3,1}
and this is my code :(! Thanks alot!
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;
}
So, the numbers 1 to 10 should be sorted as
{2,4,6,8,10,9,7,5,3,1}?Without looking at your code, I can tell you that you don’t need two quicksort functions.
Just let even numbers compare less than odd numbers. Numbers of the same parity compare as specified.