Skip to content

Instantly share code, notes, and snippets.

@justinAurand
Last active December 21, 2015 10:59
Show Gist options
  • Save justinAurand/6296139 to your computer and use it in GitHub Desktop.
Save justinAurand/6296139 to your computer and use it in GitHub Desktop.
Pancake sort w/ coded array reversals.
using System;
class PancakeSort
{
public static void Main(string[] args)
{
// Make sure console arguments have been entered.
if (args.Length <= 0)
{
Console.WriteLine("You must enter at least one string to pancake sort.");
Console.ReadKey();
return;
}
// Display items before sorting.
Console.WriteLine("You entered the following console arguments:");
foreach (string arg in args)
Console.WriteLine(arg);
Console.WriteLine();
// Determine portion of stack to be evaluated / sorted.
int sortableEndpoint = args.Length - 1;
// Define arguments to hold range for portion of stack to be flipped.
int topSwap, bottomSwap;
// Define argument to hold index of the largest string.
int largestItemIndex;
// Execute the pancake sort as long as we're evaluating at least two elements.
while (sortableEndpoint >= 1)
{
// Set / Reset index of largest string.
largestItemIndex = 0;
// Find and store index of largest string.
for (int i = 1; i <= sortableEndpoint; i++)
if (args[i].Length > args[largestItemIndex].Length)
largestItemIndex = i;
// Don't do either of the two flips if the largest item is already on the bottom of the evaluated stack.
if (largestItemIndex != sortableEndpoint)
{
// Don't do the 1st flip if the largest item is already on top.
if (largestItemIndex != 0)
{
// Determine indexes for 1st flip.
topSwap = 0;
bottomSwap = largestItemIndex;
// Execute 1st flip.
while (bottomSwap > topSwap)
{
// Swap outter items.
string temp = args[topSwap];
args[topSwap] = args[bottomSwap];
args[bottomSwap] = temp;
// Move inward.
topSwap++;
bottomSwap--;
}
}
// Determine indexes for 2nd flip.
topSwap = 0;
bottomSwap = sortableEndpoint;
// Execute 2nd flip.
while (bottomSwap > topSwap)
{
// Swap outter items.
string temp = args[topSwap];
args[topSwap] = args[bottomSwap];
args[bottomSwap] = temp;
// Move inward.
topSwap++;
bottomSwap--;
}
}
// Moved largest item to bottom of sortable stack. Move endpoint to not evaluate that item again.
sortableEndpoint--;
}
// Display items after sorting.
Console.WriteLine("Arguments after pancake sort:");
foreach (string arg in args)
Console.WriteLine(arg);
// Pause at the end of execution.
Console.ReadKey();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment