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

โปรแกรม C พิมพ์ค่าที่ไม่ซ้ำในอาร์เรย์และเรียงลำดับ (Sorted Distinct Elements)

โจทย์

กำหนดอาร์เรย์จำนวนเต็ม ให้ลบค่าซ้ำ และพิมพ์ค่าที่ไม่ซ้ำ (distinct) เรียงจากน้อยไปมาก

ตัวอย่าง

Input: {4, 6, 5, 3, 4, 5, 2, 8, 7, 0}
Output: 0 2 3 4 5 6 7 8

วิธีการ

  1. หาค่าที่ไม่ซ้ำ: วนลูปเปรียบเทียบแต่ละค่ากับค่าที่อยู่หลัง ถ้าไม่เจอซ้ำ ใส่ในอาร์เรย์ใหม่
  2. เรียงลำดับอาร์เรย์ใหม่ (Bubble Sort หรือ Selection Sort)
  3. พิมพ์ผลลัพธ์

อัลกอริทึม

  1. สร้างอาร์เรย์ array1[] เก็บค่า distinct, count = 0
  2. ลูป i=0 ถึง size-1: ลูป j=i+1 ถึง size-1 ถ้า array[i]==array[j] break; ถ้า j==size → array1[count++] = array[i]
  3. เรียง array1 ด้วย nested loop swap
  4. พิมพ์ array1

โค้ดภาษา C

#include <stdio.h>

void printDistinctElements(int array[], int size) {
    int i, j, array1[size], temp, count = 0;
    
    // หาค่าที่ไม่ซ้ำ
    for (i = 0; i < size; i++) {
        for (j = i + 1; j < size; j++) {
            if (array[i] == array[j]) break;
        }
        if (j == size)  // ไม่เจอซ้ำ
            array1[count++] = array[i];
    }
    
    // เรียงลำดับ (Bubble Sort แบบง่าย)
    for (i = 0; i < count - 1; i++) {
        for (j = i + 1; j < count; j++) {
            if (array1[i] > array1[j]) {
                temp = array1[i];
                array1[i] = array1[j];
                array1[j] = temp;
            }
        }
    }
    
    for (i = 0; i < count; ++i)
        printf("%d ", array1[i]);
}

int main() {
    int array[] = {4, 6, 5, 3, 4, 5, 2, 8, 7, 0};
    int n = sizeof(array) / sizeof(array[0]);
    printDistinctElements(array, n);
    return 0;
}

ผลลัพธ์

0 2 3 4 5 6 7 8