王道书 P360 T03(计数排序)

/**
 * 王道书 P360 T03 计数排序
 * 可以和王道书 P361 T05 比较思考一下,
 * T05是在比较时比较的元素两者都进行count++了,
 * 所以下一轮的时候就不用从a[0]开始了,减少了不必要的比较次数。
 * 但是 T05 又开了数组 B[],除此之外还有 count[];
 * 而 T03 只开了数组 temp[],额外占用的空间更小。
 *
 * ①算法思想
 *
 * ②算法设计
 *
 */

#include <stdio.h>
#include <iostream>
#include <cstdio>
#include <malloc.h>
#include <cstdlib>
#define MaxSize 20
#define INF 999999

//王道书 P360 T03 计数排序
void CountSort(int arr[],int n){
    int count;
    int *temp = (int*)malloc(sizeof(int) * n);
    for (int i = 0; i < n; ++i) {
        count = 0;
        for (int j = 0; j < n; ++j) {
            if (arr[i] > arr[j])
                count++;
        }
        temp[count] = arr[i];
    }
    for (int i = 0; i < n; ++i) {
        arr[i] = temp[i];
    }
    free(temp);
}

int main(){
    int arr[] = {2,3,4,5,1};
    CountSort(arr,5);
    for (int i = 0; i < 5; ++i) {
        printf("%d ",arr[i]);
    }
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值