/// <summary> /// Compares pairs of values and swaps them if /// </summary> public static string BubbleSort(string stringToSort, bool ascending) { int stringLength = stringToSort.Length; StringBuilder stringBuilder = new StringBuilder(stringToSort); int changesMade = 0; do // Run the code block at least once in any case { changesMade = 0; // Compare character of current index to the next one in the string // Use their ASCII codes. For example, let's say that (int) 'c' = 3; (int) 'a' = 1. // If current code is higher than next one, swap the corresonding characters' places. for (int i = 0; i < stringLength - 1; i++) { int charCurrentCode = (int)stringBuilder[i]; int charCompareToCode = (int)stringBuilder[i + 1]; bool shouldSwapCharacters = ascending ? (charCurrentCode > charCompareToCode) : (charCurrentCode < charCompareToCode); if (shouldSwapCharacters) { StringBuilderModifier.SwapCharacters(stringBuilder, i, i + 1); changesMade++; } } } while (changesMade != 0); return(stringBuilder.ToString()); }
// (From https://www.geeksforgeeks.org/gnome-sort-a-stupid-one/) /// <summary> /// Garden Gnome looks at the flower pot next to him and the previous one. /// If they are in the right order he steps one pot forward, otherwise he swaps them and steps one pot backwards. /// </summary> /// <returns></returns> public static string GnomeSort(string stringToSort, bool ascending) { StringBuilder stringBuilder = new StringBuilder(stringToSort); int currentIndex = 1; // Important! Start from 1 to avoid checking array[-1]; int stringLength = stringToSort.Length; while (currentIndex < stringLength) { // Check if the value at the current index is lower (higher) than value at the previous index; // If it is - swap them and take a step back (check the newly created pair); int currentCharCode = (int)stringBuilder[currentIndex]; int previousCharCode = (int)stringBuilder[currentIndex - 1]; bool shouldSwap = (ascending) ? (currentCharCode < previousCharCode) : (currentCharCode > previousCharCode); if (shouldSwap) { // Perform the swap StringBuilderModifier.SwapCharacters(stringBuilder, currentIndex, currentIndex - 1); // Don't go to the index of 0, because there's no other index before it // Increment the current index if you're at the first position, because you've already checked it; if (currentIndex - 1 > 0) { currentIndex -= 1; } else { currentIndex += 1; } } else { currentIndex += 1; } } return(stringBuilder.ToString()); }