ต่อไปนี้เป็นโปรแกรม Java สำหรับการหมุนอาร์เรย์ -
ตัวอย่าง
public class Demo{
void rotate_left(int my_arr[], int d, int len){
d = d % len;
int i, j, k, temp;
int divisor = greatest_Common_divisor(d, len);
for (i = 0; i < divisor; i++){
temp = my_arr[i];
j = i;
while (true){
k = j + d;
if (k >= len)
k = k - len;
if (k == i)
break;
my_arr[j] = my_arr[k];
j = k;
}
my_arr[j] = temp;
}
}
void display_arr(int my_arr[], int size){
int i;
for (i = 0; i < size; i++)
System.out.print(my_arr[i] + " ");
}
int greatest_Common_divisor(int a, int b){
if (b == 0)
return a;
else
return greatest_Common_divisor(b, a % b);
}
public static void main(String[] args){
Demo my_inst = new Demo();
int my_arr[] = { 5, 7, 89, 91, 34, 21, 11, 0 };
System.out.println("Rotating the array to the left ");
my_inst.rotate_left(my_arr, 2, 8);
System.out.println("Displaying the array from a specific index ");
my_inst.display_arr(my_arr, 8);
}
} ผลลัพธ์
Rotating the array to the left Displaying the array from a specific index 89 91 34 21 11 0 5 7
คลาสชื่อ Demo มีฟังก์ชันสแตติกชื่อ 'rotate_left' ในที่นี้ อาร์เรย์จะถูกส่งผ่านเป็นหนึ่งในพารามิเตอร์ของฟังก์ชัน 'd' คือจำนวนที่อาร์เรย์ควรจะหมุน และ 'len' คือขนาดของอาร์เรย์ ฟังก์ชัน 'greatest_common_divisor' ถูกเรียกโดยการส่งผ่านค่าของ 'd' และ 'len' วนรอบ 'for' ซ้ำกับผลลัพธ์ของการเรียกใช้ฟังก์ชันไปที่ 'greatest_common_divisor'
ฟังก์ชันชื่อ 'display_arr' ถูกกำหนดไว้เพื่อใช้แสดงองค์ประกอบอาร์เรย์ ฟังก์ชันอื่น 'greatest_Common_divisor' ถูกกำหนดให้ค้นหาตัวหารร่วมมากระหว่างตัวเลขสองตัว ซึ่งเป็นฟังก์ชันแบบเรียกซ้ำ ในฟังก์ชันหลัก อินสแตนซ์ของคลาสจะถูกสร้างขึ้น มีการกำหนดอาร์เรย์ด้วย และมีการเรียกใช้ฟังก์ชันบนอ็อบเจ็กต์นี้ ข้อมูลที่เกี่ยวข้องจะแสดงโดยใช้ฟังก์ชัน 'display_arr'