编一个C++程序 创建一个选择排序法的函数模板sort 并在main()执行

2020-05-30 科技 116阅读
写了两段代码,第一个是用冒泡排序法做的,第二个是快速排序法
#include
using namespace std;
//冒泡排序法
template
void sort(T *data, int n)
{
int i, j;
T hold;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n -1; j++)
{
if (data[j] > data[j+1])
{
hold = data[j];
data[j] = data[j+1];
data[j+1] = hold;
}
}
}
}
int main()
{
int i;
int a[] = {3, 2, 1, 5, 8 ,7};
char b[] = {'b', 'c', 'a', 'p', 'g'};
double c[] = {1.2, 2.1, 1.1, 1.0};
sort(a, 6);
for (i = 0; i < 6; i++)
cout << a[i] << " ";
cout << endl;
sort(b, 5);
for (i = 0; i < 5; i++)
cout << b[i] << " ";
cout << endl;
sort(c, 4);
for (i = 0; i < 4; i++)
cout << c[i] << " ";
cout << endl;
return 0;
}
#include
using namespace std;
//快速排序法
template
void Quick_sort(T *data_ptr, int left, int right)
{
int low(left), high(right);
T middle, temp;
middle = data_ptr[(rand()%(right - left + 1)) + left]; //随机产生一个大于等于left且小于等于right的数
do{
while ((data_ptr[low] < middle) && (low < right)) //左扫面找出大于middle的数
low++;
while ((data_ptr[high]) > middle && (high > left)) //右扫面找出小于middle的数
high--;
//数据交换
if (low <= high)
{
temp = data_ptr[low];
data_ptr[low] = data_ptr[high];
data_ptr[high] = temp;
low++;
high--;
}
}while(low <= high); //当下标交错时停止,结束一次排序
//当左边有部分值的时候(left if (left < high)
Quick_sort(data_ptr, left, high);
//当右边有部分值的时候(right > low),递归右边
if (right > low)
Quick_sort(data_ptr, low, right);
}
int main()
{
int i;
int a[] = {3, 2, 1, 5, 8 ,7};
char b[] = {'b', 'c', 'a', 'p', 'g'};
double c[] = {1.2, 2.1, 1.1, 1.0};
Quick_sort(a, 0, 5);
for (i = 0; i < 6; i++)
cout << a[i] << " ";
cout << endl;
Quick_sort(b, 0, 4);
for (i = 0; i < 5; i++)
cout << b[i] << " ";
cout << endl;
Quick_sort(c, 0, 3);
for (i = 0; i < 4; i++)
cout << c[i] << " ";
cout << endl;
return 0;
}
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com