template (1)

#include
template
void swap(T a, T b)
{
    int x = *a;
    *a = *b;
    *b = x;
}
template
void sort(M arr, int len)
{
    int i = 0;
    int j = 0;
    for (j=0; j        for (i=0; i            if (arr[i] > arr[i+1]) {
                swap(&arr[i], &arr[i+1]);
            }
        }
    }
}
template
int find(T arr[], int len, M element)
{
    int left = 0;
    int right = len-1;
    int middle = 0;
    while (left < right) {
        middle = (left+right)/2;
        if (element < arr[middle]) {
            right = middle;
        } else if (element > arr[middle]) {
            left = middle+1;
        } else
            return arr[middle];
    }
    return -1;
}

void test()
{
    int i = 0;
    int result = 0;
    int element = 0;
    //int arr[5] = {4, 3, 6, 2, 1};
    char arr[5] = {4, 3, 6, 2, 1};
    sort(arr, 5);
    for (i=0; i<5; i++)
        printf("%d ", arr[i]);
    printf("please input a number to find\n");
    scanf("%d", &element);
    result = find(arr, 5, element);
    printf("result: %d\n", result);
}
int main(int argc, char **argv)
{
    test();
}

转载于:https://www.cnblogs.com/roadmap99/p/6761395.html

你可能感兴趣的:(template (1))