洗牌陣列內容
此演算法將讀取一個數組並隨機打亂陣列內容。這將生成陣列元素的隨機排列。
為了解決這個問題,我們將從最後索引開始,隨機產生陣列中的一個索引並交換元素。
輸入和輸出
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP