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

โปรแกรม C เรียงอาร์เรย์จากน้อยไปมาก (Ascending)

ปัญหา: เรียงลำดับอาร์เรย์ตัวเลขจากน้อยไปมาก

ใช้ Bubble Sort แบบง่าย: วนลูปเปรียบเทียบคู่ที่อยู่ติดกัน สลับที่ถ้าหน้ามากกว่าหลัง

ตรรกะการเรียง

for (i = 0; i < n; ++i) {
    for (j = i + 1; j < n; ++j) {
        if (num[i] > num[j]) {
            a = num[i];
            num[i] = num[j];
            num[j] = a;
        }
    }
}

โค้ด C เต็ม

#include <stdio.h>

void main() {
    int num[20];
    int i, j, a, n;
    printf("enter number of elements in an array\n");
    scanf("%d", &n);
    printf("Enter the elements\n");
    for (i = 0; i < n; ++i)
        scanf("%d", &num[i]);
    for (i = 0; i < n; ++i) {
        for (j = i + 1; j < n; ++j) {
            if (num[i] > num[j]) {
                a = num[i];
                num[i] = num[j];
                num[j] = a;
            }
        }
    }
    printf("The numbers in ascending order is:\n");
    for (i = 0; i < n; ++i) {
        printf("%d\n", num[i]);
    }
}

ตัวอย่าง Output

enter number of elements in an array 5
Enter the elements
12 23 89 11 22
The numbers in ascending order is:
11
12
22
23
89