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

Sort Elements ระหว่าง Multiples of K ใน Array ใน C++

สมมติมี Array A และ Integer K ต้อง Sort Elements ที่อยู่ระหว่าง Multiples of K 2 ตัว ตัวอย่าง A=[2,13,3,1,21,7,8,13,12], K=2 Output=[2,1,3,7,13,21,8,13,12] Multiples of 2 คือ 2, 8, 12 Elements ระหว่าง 2 และ 8 คือ 13,3,1,21,7 เรียงได้ 1,3,7,13,21 ระหว่าง 8 และ 12 มีแค่ 13 เรียงแล้ว

Traverse Array ติดตาม Multiple ของ K เริ่มจาก Multiple ที่ 2 เรียง Elements ระหว่าง Current และ Previous Multiple

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

#include <iostream>
#include <algorithm>
using namespace std;

void display(int arr[], int n) {
    for (int i = 0; i < n; i++)
        cout << arr[i] << " ";
}

void sortBetweenMultipleOfK(int arr[], int n, int k) {
    int prev_index = -1;
    for (int i = 0; i < n; i++) {
        if (arr[i] % k == 0) {
            if (prev_index != -1) // not first multiple
                sort(arr + prev_index + 1, arr + i);
            prev_index = i;
        }
    }
}

int main() {
    int arr[] = {2, 13, 3, 1, 21, 7, 8, 13, 12};
    int n = sizeof(arr) / sizeof(arr[0]);
    int k = 2;
    cout << "Before Sort: "; display(arr, n);
    sortBetweenMultipleOfK(arr, n, k);
    cout << "\nAfter Sort : "; display(arr, n);
}

ผลลัพธ์

Before Sort: 2 13 3 1 21 7 8 13 12 After Sort : 2 1 3 7 13 21 8 13 12