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

โปรแกรม C ดำเนินการสองครึ่งของอาร์เรย์ (เรียงครึ่งแรกขึ้น ครึ่งหลังลง)


คำอธิบายปัญหา

รับอาร์เรย์ 1 มิติ N องค์ประกอบ แบ่งเป็น 2 ครึ่ง เรียงครึ่งแรก Ascending (น้อยไปมาก) และครึ่งหลัง Descending (มากไปน้อย)

ตรรกะ

  • b = n/2 (จุดกึ่งกลาง)
  • ครึ่งแรก (0 ถึง b-1): Bubble Sort Ascending
  • ครึ่งหลัง (b ถึง n-1): Bubble Sort Descending

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

#include <stdio.h>

void main() {
    int i, j, a, n, b, number[30];
    printf("Enter N: "); scanf("%d", &n);
    b = n / 2;
    printf("Enter numbers:\n");
    for (i = 0; i < n; i++) scanf("%d", &number[i]);
    // ครึ่งแรก Ascending
    for (i = 0; i < b; i++)
        for (j = i+1; j < b; j++)
            if (number[i] > number[j]) {
                a = number[i]; number[i] = number[j]; number[j] = a;
            }
    // ครึ่งหลัง Descending
    for (i = b; i < n; i++)
        for (j = i+1; j < n; j++)
            if (number[i] < number[j]) {
                a = number[i]; number[i] = number[j]; number[j] = a;
            }
    printf("1st half (asc): ");
    for (i = 0; i < b; i++) printf("%d ", number[i]);
    printf("\n2nd half (desc): ");
    for (i = b; i < n; i++) printf("%d ", number[i]);
}

ผลลัพธ์

N = 10
Numbers: 20 34 23 11 45 56 78 98 76 54
1st half (asc): 11 20 23 34 45
2nd half (desc): 98 78 76 56 54