C++练习(面向对象例题二)

习题

在这里插入图片描述

代码

#include<iostream>
#include<string.h>
#include<time.h> 
#include<stdlib.h> 
using namespace std;

class STR{
	private:
	    char s1[80],s2[80],s3[160];
	public:
	    STR(char a[],char b[]){
	    	for(int i = 0;i < strlen(a);i++)
	    	    s1[i] = a[i];
	    	for(int j = 0;j < strlen(b); j++)
	    	    s2[j] = b[j];
		}
		void ConSort();
		void Sort(char str[]); 
		void QuickSort(char str[],int low,int high);
		void Show(){
			cout << "s1 :" << s1 << endl;
			cout << "s2 :" << s2 << endl;
			cout << "s3 :" << s3 << endl;
		} 
};
void STR::ConSort(){
	//拼接
	int length1 = strlen(this->s1);
	int length2 = strlen(this->s2);
	for(int i = 0; i < length1 + length2; i++){
		if(i < length1)
		    this->s3[i] = this->s1[i];
		else
		    this->s3[i] = this->s2[i-length1];
	}
	//排序
	this->Sort(this->s3); 
}

//排序一(交换排序.冒泡排序) 
//void STR::Sort(char str[]){
//	int length = strlen(str);
//	bool tag = true;
//	char temp;
//	for(int i = 0;i < length - 1; i++){
//		tag = true;
//		for(int j = length - 1;j > i;j--){
//			if(str[j] < str[j-1]){
//				temp = str[j];
//				str[j] = str[j-1];
//				str[j-1] = temp;
//				tag = false;
//			}
//		}
//		if(tag)
//		    break;
//	} 
//}
//排序二(交换排序.快排)
void STR::Sort(char str[]){
	//以当前时间作为一个开始随机种子
	srand((unsigned)time(NULL)); 
	this->QuickSort(str,0,strlen(str)-1);
}

void STR::QuickSort(char str[],int low,int high){
	int low_ = low,high_ = high;
	//随机基准,[low,high]
	int index = rand() % (high - low + 1) + low;
	//基准与low数据交换,保证low指向基准
	if(index != low){
	    char temp = str[low];
	    str[low] = str[index];
	    str[index] = temp; 
	}
	//增设哨兵位,存放基准数据,减少数据交换次数
	char mid = str[low];
	 bool isHigh = false;
	 while(low < high){
	 	if(str[high] < mid && !isHigh){
	 		str[low] = str[high];
	 		isHigh = true;
		 }
	 	if(!isHigh)
	 	    high--;
	 
	 	if(str[low] > mid && isHigh){
	 		str[high] = str[low];
	 		isHigh = false;
		 }
		 if(isHigh)
		     low++;
	 }
	 str[low] = mid;
	 
	 if (low > (low_))
	     this->QuickSort(str,low_,low-1);
	 if(low < high_)
	     this->QuickSort(str,low+1,high_);
}

int main(){
	char s1[80],s2[80];
	cin >> s1;
	cin.get();//读换行
	cin >> s2;
	cin.get(); 
	STR str(s1,s2);
	str.ConSort();
	str.Show();
	return 0;
} 

运行结果

输入两个字符数组,拼接后排序
在这里插入图片描述

例题来源

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值