Created
June 11, 2015 18:16
-
-
Save VegaFromLyra/93833771e22f49de5525 to your computer and use it in GitHub Desktop.
In place shuffle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace InplaceShuffle | |
{ | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var arr = new int[]{1, 2, 3, 4, 5}; | |
shuffle(arr); | |
Console.WriteLine("Shuffled array is"); | |
foreach (var item in arr) | |
{ | |
Console.Write(item + " "); | |
} | |
Console.WriteLine(); | |
} | |
static void shuffle(int[] arr) { | |
Random random = new Random(); | |
for(int i = 0; i < arr.Length - 1; i++) { | |
int randomIndex = random.Next(i, arr.Length); | |
int temp = arr[i]; | |
arr[i] = arr[randomIndex]; | |
arr[randomIndex] = temp; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment