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

โปรแกรม C++ จัดเรียงสมาชิกอาร์เรย์ที่หาร x ลงตัว ให้เรียงเพิ่มขึ้น


เราได้รับอาร์เรย์จำนวนเต็ม int arr[] และตัวแปรจำนวนเต็ม x งานคือจัดเรียงสมาชิกในอาร์เรย์ที่หาร x ลงตัว (เป็นพหุคูณของ x) ให้เรียงลำดับเพิ่มขึ้น ในขณะที่สมาชิกที่ไม่ใช่พหุคูณของ x คงตำแหน่งเดิมไว้

ตัวอย่างการทำงาน (Input/Output)

ตัวอย่างที่ 1

Input: int arr[] = {4, 24, 3, 5, 7, 22, 12, 10}, int x = 2

Output: Rearrangement of all elements of array which are multiples of x 2 in increasing order is: 4 10 3 5 7 12 22 24

คำอธิบาย: พหุคูณของ 2 คือ 4, 24, 22, 12, 10 เรียงเพิ่มขึ้นได้ 4, 10, 12, 22, 24 วางกลับตำแหน่งเดิมของพหุคูณ: 4, 10, 3, 5, 7, 12, 22, 24

ตัวอย่างที่ 2

Input: int arr[] = {4, 24, 3, 5, 7, 22, 12, 10}, int x = 3

Output: Rearrangement of all elements of array which are multiples of x 3 in increasing order is: 4 3 12 5 7 22 24 10

คำอธิบาย: พหุคูณของ 3 คือ 3, 24, 12 เรียงเพิ่มขึ้นได้ 3, 12, 24 วางกลับตำแหน่งเดิม: 4, 3, 12, 5, 7, 22, 24, 10

อัลกอริทึมที่ใช้

  • ประกาศอาร์เรย์ คำนวณขนาด ประกาศตัวแปร x
  • เรียกฟังก์ชัน Rearrange_Elements(arr, size, x)
  • ภายในฟังก์ชัน:
    • สร้าง vector vec เก็บพหุคูณของ x
    • วนลูปตรวจสอบ if (arr[i] % x == 0) ให้ vec.push_back(arr[i])
    • เรียง vec ด้วย sort(vec.begin(), vec.end())
    • วนลูปอีกครั้ง ถ้า arr[i] % x == 0 ให้แทนค่าด้วย vec[j++]
    • พิมพ์อาร์เรย์ผลลัพธ์

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

#include <bits/stdc++.h>
using namespace std;

void Rearrange_Elements(int arr[], int size, int x) {
    vector<int> vec;
    int j = 0;
    for (int i = 0; i < size; i++) {
        if (arr[i] % x == 0) {
            vec.push_back(arr[i]);
        }
    }
    sort(vec.begin(), vec.end());
    for (int i = 0; i < size; i++) {
        if (arr[i] % x == 0) {
            arr[i] = vec[j++];
        }
    }
    cout << "Rearrangement of all elements of array which are multiples of x " << x << " in increasing order is: ";
    for (int i = 0; i < size; i++) {
        cout << arr[i] << " ";
    }
}

int main() {
    int arr[] = {4, 24, 3, 5, 7, 22, 12, 10};
    int x = 2;
    int size = sizeof(arr) / sizeof(arr[0]);
    Rearrange_Elements(arr, size, x);
    return 0;
}

ผลลัพธ์

การรันโค้ดข้างต้นจะได้ผลลัพธ์ดังนี้:

Rearrangement of all elements of array which are multiples of x 2 in increasing order is: 4 10 3 5 7 12 22 24