“`”

参考回答:

<pre><code>class Solution {
public:
int *sort(int *a,int lenA,int *b,int lenB){
fastSort(a,0,lenA);
fastSort(b,0,lenB);
return merge(a,lenA,b,lenB);
}
private:
</code></pre>

//快速排序

<pre><code>void fastSort(int *a,int start,int end){
if(a==NULL || end-start<=1 || start<0)
return;
int pivotPos = start;
int pivot = a[start];
int temp;
for(int i=start+1;i<end;++i){
if(a[i]<pivot){
if(++pivotPos!=i){
temp = a[i];
a[i] = a[pivotPos];
a[pivotPos] = temp;
}
}
}
a[start] = a[pivotPos];
a[pivotPos] = pivot;
fastSort(a,start,pivotPos-1);
fastSort(a,pivotPos+1,end);
}
</code></pre>

//两路归并

<pre><code>int *merge(int *a,int lenA,int *b,int lenB){
if(a==NULL || lenA<=0)
return b;
if(b==NULL || lenB<=0)
return a;
int *arry = new int[lenA+lenB];
if(arry==NULL){
</code></pre>

cerr << ""内存分配失败"" << endl;

<pre><code>exit(1);
}
int posA = 0, posB = 0 ,pos = 0;
while(posA<lenA && posB<lenB){
if(a[posA]<b[posB])
arry[pos++] = a[posA++];
else
arry[pos++] = b[posB++];
}
while(posA<lenA)
arry[pos++] = a[posA++];
while(posB<lenB)
arry[pos++] = b[posB++];
return arry;
}
};

</code></pre>

 

<pre><code> "“`

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.