Skip to content

Instantly share code, notes, and snippets.

@s0ren
Created February 22, 2018 04:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save s0ren/69a96994fc9b20ef6b81a141fec6232a to your computer and use it in GitHub Desktop.
Save s0ren/69a96994fc9b20ef6b81a141fec6232a to your computer and use it in GitHub Desktop.
Indsættelsessortering med c#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] currentDeck = { 4, 12, 8, 5, 8 };
int[] newDeck = new int[currentDeck.Length];
Console.Write("CurrentDeck er: ");
for (int i = 0; i < currentDeck.Length; i++)
{
Console.Write("{0} ", currentDeck[i]);
}
Console.WriteLine();
int cardsLeft = currentDeck.Length;
int insertedCards = 0;
// Så længe der er kort i currentDeck
while (cardsLeft > 0)
{
// find højeste kort i currentDeck
int highestCardValue = 0;
int highestCardIndex = -1;
for (int i = 0; i < currentDeck.Length; i++)
{
if (highestCardValue < currentDeck[i])
{
highestCardValue = currentDeck[i];
highestCardIndex = i;
}
}
// indsæt dette bagerst i newDeck
newDeck[insertedCards++] = highestCardValue;
// "slet" kortet fra currentDeck
currentDeck[highestCardIndex] = -1;
cardsLeft--;
}
// Slut på : Så længe der er kort i currentDeck
Console.Write("CurrentDeck er: ");
for (int i = 0; i < currentDeck.Length; i++)
{
Console.Write("{0} ", currentDeck[i]);
}
Console.WriteLine();
Console.Write("newDeck er: ");
for (int i = 0; i < newDeck.Length; i++)
{
Console.Write("{0} ", newDeck[i]);
}
Console.WriteLine();
/***********************************************************/
Console.WriteLine("List version");
List<int> oldDeck = new List<int> { 12, 5, 9, 2, 3 };
List<int> sortedDeck = new List<int>(5);
// Så længe der er kort i currentDeck
while (oldDeck.Count() > 0)
{
// find højeste kort i currentDeck
int highestCardValue = oldDeck.Max();
int highestCardIndex = oldDeck.IndexOf(highestCardValue);
// indsæt dette bagerst i newDeck
sortedDeck.Add(highestCardValue);
// "slet" kortet fra currentDeck
oldDeck.RemoveAt(highestCardIndex);
}
// Slut på : Så længe der er kort i currentDeck
foreach (int card in sortedDeck)
{
Console.Write("{0} ", card);
}
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment