Skip to content

Commit 731aec2

Browse files
authored
Shuffle the array
1 parent af4fb3a commit 731aec2

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

shuffle array.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import random
2+
3+
# A function to generate a random permutation of arr[]
4+
def randomize (arr, n):
5+
# Start from the last element and swap one by one. We don't
6+
# need to run for the first element that's why i > 0
7+
for i in range(n-1,0,-1):
8+
# Pick a random index from 0 to i
9+
j = random.randint(0,i+1)
10+
11+
# Swap arr[i] with the element at random index
12+
arr[i],arr[j] = arr[j],arr[i]
13+
return arr
14+
15+
# Driver program to test above function.
16+
arr = [1, 2, 3, 4, 5, 6, 7, 8]
17+
n = len(arr)
18+
print(randomize(arr, n))

0 commit comments

Comments
 (0)