zoukankan      html  css  js  c++  java
  • 看起来很简单,但是实际应用时可能会有意外

    看起来很简单,但是实际应用时可能会有意外,继承的概念在程序 世界与现实世界并不完全相同。 

     1 #include <iostream>
     2 
     3 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
     4 
     5 #include<string.h>
     6 
     7 using namespace std;
     8 //显示数组的函数模板
     9 template <class T> void arr_put(T arr[],int size) {
    10     for (int i=0 ;i<size;i++)
    11         cout<<arr[i]<<" ";
    12     cout<<endl;
    13 }
    14 
    15 //选择法对数组排序的函数模板
    16 template <class T> void sort(T arr[],int size) {
    17     T temp;
    18     int i,j;
    19     for (i=0;i<size-1;i++)
    20         for (j=i+1;j<size;j++)
    21             if (arr[i]>arr[j])
    22             {
    23                temp=arr[i];
    24                arr[i]=arr[j];
    25                arr[j]=temp;
    26             }
    27 }
    28 
    29 //二分查找法的函数模板
    30 template <class T> int binary_search(T array[], T value, int size)
    31 {
    32     int found = 0;
    33     int high = size, low = 0, mid;
    34 
    35     mid = (high + low) / 2;
    36 
    37     cout<<"Looking for "<<value<<endl;
    38     while ((! found) && (high >= low))
    39     {
    40       if (value == array[mid])
    41         found = 1;
    42       else if (value < array[mid])
    43         high = mid - 1;
    44       else
    45         low = mid + 1;
    46         mid = (high + low) / 2;
    47     }
    48     return((found) ? mid: -1);
    49 }
    50 
    51 //main()函数中使用处理数组的函数模板
    52 
    53 int main(int argc, char** argv) {
    54     
    55     //处理int型数组
    56     int array[10]={1,3,5,7,9,2,4,6,8,10};
    57     
    58     //显示数组初值
    59     arr_put(array,10);
    60     
    61     //对数组排序并显示
    62     sort(array,10);
    63     arr_put(array,10);
    64 
    65     //查找数组
    66     cout<<"Result of search: "<<binary_search(array, 3, 10)<<endl;
    67     cout<<"Result of search: "<<binary_search(array, 2, 10)<<endl;
    68     cout<<"Result of search: "<<binary_search(array, 9, 10)<<endl;
    69     cout<<"Result of search: "<<binary_search(array, 5, 10)<<endl;
    70     cout<<"------------------------------"<<endl;
    71 
    72     //处理字符串型数组
    73     char ch1,str[]="happy";
    74     int size=strlen(str);
    75     
    76     //显示数组初值
    77     arr_put(str,size);
    78     
    79     //对数组排序并显示
    80     sort(str,size);
    81     arr_put(str,size);
    82 
    83     //查找数组
    84     cout<<"Input a char:";
    85     cin>>ch1;
    86     cout<<"Result of search: "<<binary_search(str, ch1, size)<<endl;
    87     return 0;
    88 }
  • 相关阅读:
    svn笔记
    cakephpurl生成
    cakephp加载流程
    jquery validate使用方法
    我需要具备的知识和能力总结
    cakePHP国际化和本地化
    javascript片段收集
    ecmall一个典型的操作
    9. Technical Overview 技术概述
    42. Spring Security Dependencies春季安全依赖
  • 原文地址:https://www.cnblogs.com/borter/p/9417869.html
Copyright © 2011-2022 走看看