94 lines
2.8 KiB
C#
94 lines
2.8 KiB
C#
using System.Diagnostics;
|
|
|
|
class Program {
|
|
static void Main() {
|
|
while (true) {
|
|
Console.WriteLine();
|
|
Console.WriteLine("=== Prestanda-Sorteringsmeny ===");
|
|
Console.WriteLine("1: Bubblesort (O(n^2))");
|
|
Console.WriteLine("2: Inbyggd snabb sortering (Array.Sort)");
|
|
Console.WriteLine("0: Avsluta");
|
|
Console.Write("Ditt val: ");
|
|
|
|
var choice = Console.ReadLine();
|
|
if (choice == "0") {
|
|
Console.WriteLine("Avslutar...");
|
|
break;
|
|
}
|
|
|
|
int n = ReadPositiveInt("Hur många tal vill du sortera? ");
|
|
|
|
int[] data = CreateRandomArray(n, maxValue: n * 10);
|
|
Console.WriteLine();
|
|
Console.WriteLine($"Osorterat: {Preview(data)}");
|
|
|
|
var copy = (int[])data.Clone();
|
|
|
|
var sw = Stopwatch.StartNew();
|
|
switch (choice) {
|
|
case "1":
|
|
BubbleSort(copy);
|
|
break;
|
|
case "2":
|
|
FastSort(copy);
|
|
break;
|
|
default:
|
|
Console.WriteLine("Ogiltigt val. Försök igen.");
|
|
continue;
|
|
}
|
|
|
|
sw.Stop();
|
|
|
|
Console.WriteLine($"Sorterad: {Preview(copy)}");
|
|
Console.WriteLine($"Tid: {sw.ElapsedMilliseconds} ms för n = {n}");
|
|
}
|
|
}
|
|
|
|
static int ReadPositiveInt(string prompt) {
|
|
while (true) {
|
|
Console.Write(prompt);
|
|
if (int.TryParse(Console.ReadLine(), out int n) && n > 0)
|
|
return n;
|
|
Console.WriteLine("Ange ett heltal större än 0.");
|
|
}
|
|
}
|
|
|
|
static int[] CreateRandomArray(int n, int maxValue) {
|
|
var rnd = new Random();
|
|
var arr = new int[n];
|
|
for (int i = 0; i < n; i++)
|
|
arr[i] = rnd.Next(maxValue + 1);
|
|
return arr;
|
|
}
|
|
|
|
static string Preview(int[] arr, int head = 10, int tail = 10) {
|
|
if (arr.Length <= head + tail)
|
|
return string.Join(", ", arr);
|
|
|
|
var headPart = string.Join(", ", arr[..head]);
|
|
var tailPart = string.Join(", ", arr[^tail..]);
|
|
return $"{headPart}, … , {tailPart}";
|
|
}
|
|
|
|
public static void BubbleSort(int[] arr) {
|
|
int n = arr.Length;
|
|
bool swapped;
|
|
for (int pass = 0; pass < n - 1; pass++) {
|
|
swapped = false;
|
|
for (int i = 0; i < n - 1 - pass; i++) {
|
|
if (arr[i] > arr[i + 1]) {
|
|
int tmp = arr[i];
|
|
arr[i] = arr[i + 1];
|
|
arr[i + 1] = tmp;
|
|
swapped = true;
|
|
}
|
|
}
|
|
|
|
if (!swapped) break;
|
|
}
|
|
}
|
|
|
|
public static void FastSort(int[] arr) {
|
|
Array.Sort(arr);
|
|
}
|
|
} |