因为痛,所以叫青春

我有一个梦想:穷屌丝变身富屌丝
学而时习之,不亦乐乎。

归并排序经典代码

View Code
    #include<stdio.h>
    #define N 10000
    void Merge(int a[],int low,int mid,int high)
    {
    int m = mid+1 , n = high-mid;
    int i,x[N],y[N];
    //定义两个数组,用于分割原数组,将原数组中的元素平均非配给两个数组
    for(i = 0;i < m; i++)
    {
    x[i] = a[low+i];
    }
    for(i = 0;i < n;i++)
    {
    y[i] = a[mid+i+1];
    }
    int j = 0,k = low;
    i = 0;
    //将两个数组进行比较合并
    while(i < m && j < n)
    {
    if(x[i] < y[j])
    {
    a[k] = x[i++];
    }
    else 
    {
    a[k] = y[j++];
    }
    k++;
    }
    //将剩余的元素归并到原数组
    while(i < m)
    a[k++] = x[i++];
    while(j < n)
    a[k++] = y[j++];
    }
    void Merge_Sort(int a[],int low,int high)
    {
    //先将传递过来的数组进行递归二分
    if(low < high)
    {
    int mid = (low+high)/2;
    Merge_Sort(a,low,mid);
    Merge_Sort(a,mid+1,high);
    Merge(a,low,mid,high);
    }
    }
    void main()
    {
    int a[N],n,i;
    scanf("%d",&n);
    for( i = 0; i < n; i++)
    scanf("%d",&a[i]);
    // 直接进行调用
    Merge_Sort(a,0,n-1);
    for( i = 0; i < n; i++)
    printf("%d ",a[i]);
    }

快速排序

View Code
KMP算法
View Code
#include<stdio.h>
#include<string.h>
const int N = 1010;
    char T[1000010], P[N];
    int pi[N];
    int ans;
    void COMPUTER_PREFIX_FUNCTION(){
        int m = strlen(P), i, k;
        for(k = pi[0] = -1, i = 1; i < m; i++){
            while(k > -1 && P[k+1] != P[i])
                k = pi[k];
            if(P[k+1] == P[i])
                k++;
            pi[i] = k;
        }
    }
    void KMP_MATCHER(){
        int i, n, m, k;
        n = strlen(T); m = strlen(P);
        for(k = -1, i = 0; i < n; i++){
            while(k > -1 && P[k+1] != T[i])    k = pi[k];
            if(P[k+1] == T[i])    k++;
            if(k == m-1){
                ans ++;
                k = pi[k];
            }
        }
    }
    int main(){
        //freopen("data.in", "r", stdin);
        int n;
        scanf("%d", &n);
        while(n--) {
            scanf("%s %s", T, P);
            ans = 0;
            COMPUTER_PREFIX_FUNCTION();
            KMP_MATCHER();
            printf("%d\n", ans);
        }
        return 0;
    }

 

    #include<stdio.h>
    void sort(int a[],int low,int high)
    {
    int m = low,n = high,key = a[low];
    if(low > high)
    return;
    while(low < high)
    {
    while(low < high && key <= a[high])
    high--;
    a[low] = a[high];
    while(low < high && key >= a[low])
    low++;
    a[high] = a[low];
    }
    a[low] = key;
    sort(a,m,low-1);
    sort(a,low+1,m);
    }
    void main()
    {
    int n,i,a[100];
    scanf("%d",&n);
    for(i = 0; i < n; i++)
    scanf("%d",&a[i]);
    sort(a,0,n-1);
    for(i = 0; i < n; i++)
    printf("%d ",a[i]);
    }

posted on 2012-07-22 17:06  Nice!  阅读(194)  评论(0编辑  收藏  举报