อัลกอริธึมนี้จะใช้อาร์เรย์และสับเปลี่ยนเนื้อหาของอาร์เรย์ มันจะสร้างการเรียงสับเปลี่ยนแบบสุ่มขององค์ประกอบอาร์เรย์
เพื่อแก้ปัญหานี้ เราจะสลับองค์ประกอบโดยเริ่มจากดัชนีสุดท้ายไปเป็นดัชนีที่สร้างแบบสุ่มในอาร์เรย์
อินพุตและเอาต์พุต
Input:
An array of integers: {1, 2, 3, 4, 5, 6, 7, 8}
Output:
Shuffle of array contents: 3 4 7 2 6 1 5 8 (Output may differ for next run) อัลกอริทึม
randomArr(array, n)
ป้อนข้อมูล: อาร์เรย์ จำนวนองค์ประกอบ
ผลลัพธ์: สับเปลี่ยนเนื้อหาของอาร์เรย์
Begin for i := n – 1 down to 1, do j := random number from 0 to i swap arr[i] and arr[j] done End
ตัวอย่าง
#include <iostream>
#include<cstdlib>
#include <ctime>
using namespace std;
void display(int array[], int n) {
for (int i = 0; i < n; i++)
cout << array[i] << " ";
}
void randomArr ( int arr[], int n ) { //generate random array element
srand (time(NULL)); //use time to get different seed value to start
for (int i = n-1; i > 0; i--) {
int j = rand() % (i+1); //randomly choose an index from 0 to i
swap(arr[i], arr[j]); //swap current element with element placed in jth location
}
}
int main() {
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
int n = 8;
randomArr(arr, n);
display(arr, n);
} ผลลัพธ์
4 7 8 2 6 3 5 1