- 论坛徽章:
- 0
|
冒泡排序
#include iostream.h>
template class T>
void bubblesort(T *p, int n)
{
for(int i=0;in;i++)
coutp" "; //output the value before sort
coutendl;
int flag=1,count=0;
for(int i=0;(in-1)&&flag;i++)//attention the condition of loop
{
count++;//count the number of loop
flag=0;
for(int j=0;jn-1-i;j++)//attention the condition of loop
if(p[j]>p[j+1])
{
T temp;
temp=p[j];
p[j]=p[j+1];
p[j+1]=temp;
flag=1;
}
}
coutcountendl;
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
bubblesort(iarr,5);
coutendl;
print(iarr,5);
}
插入排序
#include iostream.h>
template class T>
void insertsort(T *p, int n)
{
for(int i=0;in;i++)//output the values before sort
coutp" ";
coutendl;
int count=0;
for(int j=1;jn;j++)
{
T temp=p[j];
while(j>0&&(tempp[j-1]))
{p[j]=p[--j];
//count++;
}
p[j]=temp;
}
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
insertsort(iarr,5);
coutendl;
print(iarr,5);
}
选择排序
#include iostream.h>
template class T>
void selectsort(T *p, int n)
{
for(int i=0;in;i++)//output the values before sort
coutp" ";
coutendl;
int count=0;
for(int j=0;jn-1;j++)
{
int h=j;
for(int k=j+1;kn;k++)
{if(p[h]>p[k])
h=k;
count++;
}
if(h!=j)
{
T temp=p[h];
p[h]=p[j];
p[j]=temp;
}
}
cout"the count= "countendl;
}
template class T>
void print(T *arr, int n)
{
for(int i=0;in;i++)
coutarr" ";
coutendl;
}
int main()
{
int arr[4]={42,52,55,68};
int iarr[5];
for(int i=0;i5;i++)
{
iarr=rand()%100;
}
selectsort(iarr,5);
coutendl;
print(iarr,5);
}
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/45689/showart_489885.html |
|