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

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


เราจะมาดูวิธีการแยกอาร์เรย์ และเพิ่มส่วนแรกหลังจากแยกที่ตำแหน่งสิ้นสุด สมมติว่าเนื้อหาอาร์เรย์คือ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} เราต้องการตัดอินโทรนี้ออกเป็นสองส่วน ส่วนแรกมาจากดัชนี 0 ถึง 3 (แยกขนาด 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;
   }
}
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