From dec3fc256354f9b7bdb5ff9fda7898470bdbfe61 Mon Sep 17 00:00:00 2001 From: Ron Zuckerman Date: Sun, 28 Jan 2024 18:14:56 -0600 Subject: [PATCH] Add Quick Sort in Beef --- archive/b/beef/QuickSort.bf | 147 ++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 archive/b/beef/QuickSort.bf diff --git a/archive/b/beef/QuickSort.bf b/archive/b/beef/QuickSort.bf new file mode 100644 index 000000000..5a1581977 --- /dev/null +++ b/archive/b/beef/QuickSort.bf @@ -0,0 +1,147 @@ +using System; +using System.Collections; + +namespace QuickSort; + +class Program +{ + public static void Usage() + { + Console.WriteLine( + """ + Usage: please provide a list of at least two integers to sort in the format "1, 2, 3, 4, 5" + """ + ); + Environment.Exit(0); + } + + public static Result ParseInt(StringView str) + where T : IParseable + { + StringView trimmedStr = scope String(str); + trimmedStr.Trim(); + + // T.Parse ignores single quotes since they are treat as digit separators -- e.g. 1'000 + if (trimmedStr.Contains('\'')) + { + return .Err; + } + + return T.Parse(trimmedStr); + } + + public static Result ParseIntList(StringView str, List arr) + where T: IParseable + { + arr.Clear(); + for (StringView item in str.Split(',')) + { + switch (ParseInt(item)) + { + case .Ok(let val): + arr.Add(val); + + case .Err: + return .Err; + } + } + + return .Ok; + } + + // Reference: https://en.wikipedia.org/wiki/Quicksort#Lomuto_partition_scheme + public static void QuickSort(List arr) + where int : operator T <=> T + { + QuickSortRec(arr, 0, arr.Count - 1); + } + + public static void QuickSortRec(List arr, int lo, int hi) + where int : operator T <=> T + { + // Exit if no enough elements + if (lo >= hi || lo < 0) + { + return; + } + + // Get partition + int p = Partition(arr, lo, hi); + + // Sort left side of partition + QuickSortRec(arr, lo, p - 1); + + // Sort right side of partition + QuickSortRec(arr, p + 1, hi); + } + + public static int Partition(List arr, int lo, int hi) + where int : operator T <=> T + { + // Set pivot to last element + T pivot = arr[hi]; + + // Set temporary pivot index + int i = lo - 1; + + for (int j in lo..(List arr) + { + String line = scope .(); + for (T val in arr) + { + if (!line.IsEmpty) + { + line += ", "; + } + + line.AppendF("{}", val); + } + + Console.WriteLine(line); + } + + public static int Main(String[] args) + { + if (args.Count < 1) + { + Usage(); + } + + List arr = scope .(); + switch (ParseIntList(args[0], arr)) + { + case .Ok: + if (arr.Count < 2) + { + Usage(); + } + case .Err: + Usage(); + } + + QuickSort(arr); + ShowList(arr); + return 0; + } +}