Skip to content

Instantly share code, notes, and snippets.

@VegaFromLyra
Created June 11, 2015 18:16
Show Gist options
  • Save VegaFromLyra/93833771e22f49de5525 to your computer and use it in GitHub Desktop.
Save VegaFromLyra/93833771e22f49de5525 to your computer and use it in GitHub Desktop.
In place shuffle
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