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

การจัดเรียงสลับกัน (Alternative Sorting) ใน C++


บทนำ

จัดเรียงอาร์เรย์จำนวนเต็มแบบ: ตัวแรก = ค่าสูงสุด, ตัวที่สอง = ค่าต่ำสุด, ตัวที่สาม = ค่าสูงสุดอันดับ 2, ตัวที่สี่ = ค่าต่ำสุดอันดับ 2, ...

ตัวอย่าง

Input: 4 1 8 2 9 3 7 → Sorted: 1 2 3 4 7 8 9 → Alternative: 9 1 8 2 7 3 4

อัลกอริทึม

  1. เรียงอาร์เรย์จากน้อยไปมาก
  2. สร้าง pointer สองตัว: i=0 (หน้า), j=n-1 (หลัง)
  3. พิมพ์ arr[j--] แล้ว arr[i++] สลับกันจน i >= j
  4. ถ้า n คี่ พิมพ์ arr[i] ตัวสุดท้าย

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

#include <iostream>
using namespace std;

void swap(int *xp, int *yp) {
    int temp = *xp; *xp = *yp; *yp = temp;
}

void selectionSort(int arr[], int n) {
    for (int i = 0; i < n-1; i++) {
        int min_idx = i;
        for (int j = i+1; j < n; j++)
            if (arr[j] < arr[min_idx]) min_idx = j;
        swap(&arr[min_idx], &arr[i]);
    }
}

void alternateSort(int arr[], int n) {
    selectionSort(arr, n);
    int i = 0, j = n - 1;
    while (i < j) {
        cout << arr[j--] << " ";
        cout << arr[i++] << " ";
    }
    if (n % 2 != 0) cout << arr[i];
}

int main() {
    int arr[] = {4, 1, 8, 2, 9, 3, 7};
    int n = sizeof(arr) / sizeof(arr[0]);
    alternateSort(arr, n);
    return 0;
}

ผลลัพธ์

9 1 8 2 7 3 4