码迷,mamicode.com
首页 > 其他好文 > 详细

ALGORITHM:Sort-CountingSort

时间:2020-05-15 00:01:57      阅读:69      评论:0      收藏:0      [点我收藏+]

标签:stat   char   sizeof   turn   print   ==   return   algorithm   ati   

#include "stdafx.h"
#include <iostream>

static void print(int arrayOld[], int n) {
    for (int i = 0; i < n; i++) {
        if (i == n - 1) {
            std::cout << arrayOld[i] << std::endl;
        }
        else {
            std::cout << arrayOld[i] << ",";
        }
    }
}

static int getMax(int a[], int n) {
    int max = a[0];
    for (int i = 0; i < n; i++) {
        if (a[i] > max) {
            max = a[i];
        }
    }
    return max;
}
static int getMin(int a[], int n) {
    int min = a[0];
    for (int i = 0; i < n; i++) {
        if (a[i] < min) {
            min = a[i];
        }
    }
    return min;
}

static void countingSort(int a[], int n, int unused[]) {
    int min = getMin(a, n)
      , max = getMax(a, n)
      , idxLen = max - min + 1
      , *idxFlg = new int[idxLen]
    ;

    memset(idxFlg, 0, sizeof(int) * idxLen);
    for (int i = 0; i < n; i++) {
        idxFlg[a[i] - min]++;
    }
    for (int i = 1; i < idxLen; i++) {
        idxFlg[i] += idxFlg[i - 1];
    }

    for (int i = n - 1; i >= 0; i--) {
        unused[idxFlg[a[i] - min] - 1] = a[i];
    }
}


int _tmain(int argc, _TCHAR* argv[]) {
    int array[10] = {18, 7,29, 2, 105, 4, 1, 61, 0, 3000};
    int dst[10] = {0};

    int n = sizeof(array) / sizeof(array[0]);
    print(array, n);
    countingSort(array, n, dst);
    print(dst, n);

    getchar();
}

 

ALGORITHM:Sort-CountingSort

标签:stat   char   sizeof   turn   print   ==   return   algorithm   ati   

原文地址:https://www.cnblogs.com/xinyueliu/p/12892233.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!