Day07_C++编程
01.思维导图
02.
请使用函数模板,写一个能够针对所有数据类型的数据的快速排序函数
并多写几个数组做测试。
快排排序函数,C++函数模板改写
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>//请使用函数模板,写一个能够针对所有数据类型的数据的快速排序函数
//并多写几个数组做测试
using namespace std;//1.一次快排需要返回最后基准的位置
template<typename T>
int on_sort(T *p,int low,int high)
{T base=*(p+low);while(high>low){//high一侧的数据比基准更大//因为内存循环中每次high和low的值都会改变所以必须交到循环里面while(*(p+high)>=base && high>low){high--;}*(p+low)=*(p+high);while(*(p+low)<=base && high>low){low++;}*(p+high)=*(p+low);}*(p+low)=base;//将基准放在中间位置return low;
}//快速排序函数
template <typename T>
void sort(T *p,int low,int high)
{int ret;if(high>low){ret=on_sort(p,low,high);sort(p,low,ret-1);sort(p,ret+1,high);}
}//打印数组函数
template <typename T>
void printArray(T *p,int size)
{for(int i=0;i<size;i++){cout<<p[i]<<" ";}cout<< endl;
}int main(int argc, const char** argv)
{//测试整数数组int intArr[]={1,55,77,22,66,99,102,27,44};int intSize=sizeof(intArr)/sizeof(intArr[0]);cout<<"整型数组一次性快排的结果:";on_sort(intArr,0,intSize-1);printArray(intArr,intSize);cout<<"整型数组完全快排的结果:";sort(intArr,0,intSize-1);printArray(intArr,intSize);//测试浮点型数组float floatArr[]={1.2,1.02,2.5,3.6,7.7,6.1,4.8};int floatSize=sizeof(floatArr)/sizeof(floatArr[0]);cout<<"浮点型数组一次性快排结果:";on_sort(floatArr,0,floatSize-1);printArray(floatArr,floatSize);cout<<"浮点型数组完全快排的结果:";sort(floatArr,0,floatSize-1);printArray(floatArr,floatSize);//测试字符型数组char charArr[]={'d','B','f','o','w','m','A','E','P','r','l','n'};int charSize=sizeof(charArr)/sizeof(charArr[0]);cout<<"字符型数组一次性快排的结果:";on_sort(charArr,0,charSize-1);printArray(charArr,charSize);cout<<"字符型数组完全快排的结果:";sort(charArr,0,charSize-1);printArray(charArr,charSize);return 0;
}
冒泡排序函数,C++函数模板改写
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sstream>
#include <vector>
#include <memory>
using namespace std;
//请使用函数模板,写一个能够针对所有数据类型的数据的冒泡排序函数
//并多写几个数组做测试//冒泡排序函数模板
template <typename T>
void bubbleSort(T arr[],int size)
{for(int i=0;i<size-1;++i){bool flag=false;for(int j=0;j<size-i-1;++j){if(arr[j]>arr[j+1]){//交换元素T temp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;flag=true;}}//如果没有发生交换,说明数组已经有序,提前退出循环if(!flag){break;}}
}//打印数组函数模板
template<typename T>
void printArray(const T arr[],int size)
{for(int i=0;i<size;++i){cout<<arr[i]<<" ";}cout<<endl;
}int main(int argc, const char** argv)
{//测试整数数组int intArr[]={1,55,77,22,66,99,102,27,44};int intSize=sizeof(intArr)/sizeof(intArr[0]);cout<<"整型数组冒泡的结果:";bubbleSort(intArr,intSize);printArray(intArr,intSize);//测试浮点型数组float floatArr[]={1.2,1.02,2.5,3.6,7.7,6.1,4.8};int floatSize=sizeof(floatArr)/sizeof(floatArr[0]); cout<<"浮点型数组冒泡的结果:";bubbleSort(floatArr,floatSize);printArray(floatArr,floatSize);//测试字符型数组char charArr[]={'d','B','f','o','w','m','A','E','P','r','l','n'};int charSize=sizeof(charArr)/sizeof(charArr[0]);cout<<"字符型数组冒泡的结果:";bubbleSort(charArr,charSize);printArray(charArr,charSize);return 0;
}