【PAT甲级复习】 专题复习十:入门模拟与算法初步

本文介绍了计算机科学中的一些基础算法概念和技术,包括日期处理、不同进制间的转换、排序算法、散列技术、快速幂运算、归并排序及快速排序等。通过具体的代码示例,帮助读者更好地理解和掌握这些基本算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

专题复习十(9.11):入门模拟与算法初步

1 日期处理

主要注意平年闰年

int month[13][2] = {	//第二维为0表示平年,为1表示闰年
    {0,0},{31,31},{28,29},{31,31},{30,30},{31,31},{30,30},{31,31},{31,31},{30,30},{31,31},{30,30},{31,31}
};
bool isLeap(int year){
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

2 进制转换

P进制x转为10进制y:

int y = 0, product = 1;
while(x != 0){
    y = y + (x % 10) * product;
    x = x / 10;
    product = product * P;
}

10进制y转换为Q进制

int z[40], num = 0;
do{
    z[num++] = y % Q;
    y = y / Q;
}while(y != 0);

3 排序

4 散列

平方探测法的k只在 [0,Tsize) 范围内寻找即可

5 快速幂

递归写法:

typedef long long LL;
LL binaryPow(LL a, LL b, LL m){
    if(b == 0) return 1;
    if(b & 1) return a * binaryPow(a, b-1, m) % m;
    else{
        LL mul = binaryPow(a, b/2, m);
        return mul * mul % m;
    }
}

6 归并排序

void merge(int A[], int L1, int R1, int L2, int R2){
    int i = L1, j = L2;
    int temp[MAXN], index = 0;
    while(i <= R1 && j <= R2){
        if(A[i] <= A[j]){
            temp[index++] = A[i++];
        }
        else{
            temp[index++] = A[j++];
        }
    }
    while(i <= R1) temp[index++] = A[i++];
    while(j <= R2) temp[index++] = A[j++];
    for(i=0; i<index; i++){
        A[L1+i] = temp[i];
    }
}


void mergeSort(int A[]){
    for(int step = 2; step / 2 <= n; step *= 2){
        for(int i=1; i<=n; i+=step){
            sort(A+i, A+min(i+step, n+1));
        }
        //此处可以输出每一趟结束的序列
    }
}

7 快速排序

int Partition(int A[], int left, int right){
    int p = round(1.0 * rand() / RAND_MAX * (right-left) + left);
    swap(A[p], A[left]);
    int temp = A[left];
    while(left < right){
        while(left < right && A[right] > temp) right--;
        A[left] = A[right];
        while(left < right && A[left] <= temp) left++;
        A[right] = A[left];
    }
    A[left] = temp;
    return left;
}

void quickSort(int A[], int left, int right){
    if(left < right){
        int pos = Partition(A, left, right);
        quickSort(A, left, pos - 1);
        quickSort(A, pos + 1, right);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值