习题
代码
#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;
}
运行结果
输入两个字符数组,拼接后排序