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

โปรแกรม C++ แยกอาร์เรย์และเพิ่มส่วนแรกต่อท้าย


ที่นี่เราจะดูวิธีแยกอาร์เรย์ และเพิ่มส่วนแรกหลังแยกไปที่ตำแหน่งสุดท้าย สมมติเนื้อหาอาร์เรย์คือ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} เราต้องการตัดเป็นสองส่วน ส่วนแรกจากดัชนี 0 ถึง 3 (split size 4) และส่วนที่สองคือส่วนที่เหลือ หลังจากเพิ่มส่วนแรกต่อท้าย องค์ประกอบอาร์เรย์จะเป็น {4, 5, 6, 7, 8, 9, 0, 1, 2, 3} เพื่อแก้ปัญหานี้ เราจะทำตามอัลกอริทึมนี้

อัลกอริทึม

splitArray(arr, n, k)

begin
    for i := 0 to k, do
        x := arr[0]
        for j := 0 to n-2, do
            arr[j] := arr[j+1]
        done
        arr[n-1] := x
    done
end

ตัวอย่าง

#include<iostream>
using namespace std;

void splitArray(int arr[], int n, int k) {
    for(int i = 0; i < k; i++) {
        int x = arr[0]; // take the first number
        for(int j = 0; j <= n - 2; j++) {
            arr[j] = arr[j+1];
        }
        arr[n-1] = x;
    }
}

int main() {
    int data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
    int n = sizeof(data) / sizeof(data[0]);
    int i;
    cout << "Enter split size: ";
    cin >> i;
    splitArray(data, n, i);
    for(int i = 0; i < n; i++) {
        cout << data[i] << " ";
    }
}

ผลลัพธ์

Enter split size: 4
4 5 6 7 8 9 0 1 2 3