C++ Exercises(七)

#include <iostream>
#include 
<string>
#include 
<cstdlib>
#include 
<ctime>
using namespace std;

template 
<typename T>
void deSelSort(T arr[],int n)
{//双端选择排序
    int min,max;
    
for (int i=0,j=n-1;i<j;++i,--j)
    
{
        min 
= i;
        max 
= j;
        
if (arr[min]>arr[max])
        
{//确保两个端点处有序
            MySwap(arr[min],arr[max]);
        }

        
for (int m=i+1;m<j;++m)
        
{
            
if (arr[m]>arr[max])
            
{
                max 
= m;
            }

            
else if(arr[m]<arr[min])
            
{
                min 
= m;
            }

        }

        
//交换最小值和最大值到合适的位置
        MySwap(arr[min],arr[i]);
        MySwap(arr[max],arr[j]);
    }


}

template 
<typename T>
void bubbleSort(T arr[] ,int n)
{//冒泡排序
    bool isSwaped;
    
for (int i=n-1;i>=1;--i)
    
{
        isSwaped 
= false;
        
for (int j=0;j<=i;++j)
        
{
            
if (arr[j]>arr[j+1])
            
{
                isSwaped 
= true;
                MySwap(arr[j],arr[j
+1]);
                
            }

        }

        
if (isSwaped==false)
        
{//没有交换,停止排序
            break;
        }

    }

}

template 
<typename T>
void MySwap(T& a,T& b)
{//交换两个值
    T temp;
    temp 
= a;
    a 
= b;
    b 
= temp;
}

template
<typename T>
void printArray(T arr[],int n)
{//输出列表
    for (int i=0;i<n;++i)
    
{
        cout
<<arr[i]<<'\t';
    }

    cout
<<endl;
}

bool isPal(const string& str,int start,int end)
{//判断是否是回文
    if (start>=end-1)
    
{
        
return true;
    }

    
else if (str[start]!=str[end-1])
    
{
        
return false;
    }

    
else
        
return isPal(str,start+1,end-1);
}

void dec2bin(int n,int length)
{//输出整数n为固定长度length的进制数字
    if (length==1)
    
{
        cout
<<"0";
        
return;
    }

    dec2bin(n
/2,length-1);
    cout
<<n%2;

}

template
<typename T>
void generateArray(T arr[],int n)
{//产生随即数数组

    srand((unsigned)time(NULL));
    
for (int i=0;i<n;++i)
    
{
        arr[i] 
= rand()%1000;
    }

}

int main(void)
{
    
int a[] = {8,7,6,5,4,3,2,1};
    cout
<<"排序前:";
    printArray(a,
8);
    deSelSort(a,
8);
    
//bubbleSort(a,8);
    cout<<"排序后:";
    printArray(a,
8);
    
string str;
    cout
<<"是否是回文";
    cin
>>str;
    cout
<<isPal(str,0,str.length())<<endl;
    
int num,len;
    cout
<<"输入数:";
    cin
>>num>>len;
    dec2bin(num,len);
    cout
<<"产生随机数数组:"<<endl;
    
int b[10];
    generateArray(b,
10);
    bubbleSort(b,
10);
    printArray(b,
10);
    
return 0;
}


posted on 2007-12-21 12:53  Phinecos(洞庭散人)  阅读(485)  评论(0编辑  收藏  举报

导航