面试题:两个无序数组合并成一个有序数组

         昨天面试,问了一个简单的算法题,当时快速排序的代码有点忘了,还想了一会儿。最后写的估计也还有点问题,再写一遍。

        思路:先分别对两个数组进行排序(可以用快速排序),然后两路归并。

#include <iostream>
using namespace std;



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:
	//快速排序
	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);
	}
	//两路归并
	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){
			cerr << "内存分配失败" << endl;
			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;
	}
};

void main()
{
	int len = 5;
	int *a = new int[len];
	int *b = new int[len];
	for(int i=0;i<len;++i){
		a[i] = rand();
		b[i] = rand();
	}
	for(int i=0;i<len;++i)
		cout << a[i] << " ";
	cout << endl;
	for(int i=0;i<len;++i)
		cout << b[i] << " ";
	cout << "\n排序后:" << endl;
	int *arry = Solution().sort(a,len,b,len);
	for(int i=0;i<2*len;++i)
		cout << arry[i] << " ";
	cout << endl;
}

        假设两个数组长度相等,均为N,则算法的时间复杂度是O(2NlogN)。

    原文作者:SHW_SEU
    原文地址: https://blog.csdn.net/nlgshw/article/details/44487989
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞