Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

Median และ Mode ด้วย Counting Sort ใน C++

พิจารณา Array ขนาด n ต้องการหา Median และ Mode ด้วย Counting Sort เหมาะเมื่อ Elements อยู่ใน Range จำกัด ตัวอย่าง {1, 1, 1, 2, 7, 1} Mode = 1, Median = 1.5

  • Median = ตัวกลางของ Sorted List
  • Mode = Element ที่เกิดบ่อยที่สุด

ขั้นตอน:

  1. Assume Array Size = n
  2. ใช้ Count Array ก่อน Sum Previous Counts
  3. Index ของ Max Value ใน Count Array คือ Mode
  4. ถ้ามี Max หลายตัว เอาตัวไหนก็ได้
  5. ดำเนิน Count Sort ต่อ
  6. ใน Sorted Array ถ้า n คี่ Median = Element กลาง ถ้า n คู่ หาค่าเฉลี่ย 2 ตัวกลาง

ตัวอย่างโค้ด C++

#include <iostream>
using namespace std;

bool isRepresentedInDDigits(int num, int d, int base) {
    if (d==1 && num < base)
        return true;
    if (d > 1 && num >= base)
        return isRepresentedInDDigits(num/base, --d, base);
    return false;
}

bool checkNumber(int num, int d) {
    for (int base=2; base<=32; base++)
        if (isRepresentedInDDigits(num, d, base))
            return true;
    return false;
}

int main() {
    int num = 8;
    int dig = 2;
    if(checkNumber(num, dig))
        cout << "Can be represented";
    else
        cout << "Can not be represented";
}

ผลลัพธ์

Can be represented