Skip to content

Instantly share code, notes, and snippets.

@jorgebv
Created April 6, 2016 05:58
Show Gist options
  • Save jorgebv/0c98dc5de6c9f24c0d5257c93fa50a91 to your computer and use it in GitHub Desktop.
Save jorgebv/0c98dc5de6c9f24c0d5257c93fa50a91 to your computer and use it in GitHub Desktop.
// 0 is log at the top of the stack, so this method should conclude
// with the intergers sorted from smallest to largest
static void SortLogs(int[] inputLogs)
{
var logsToMove = inputLogs.Length;
while (logsToMove > 0)
{
int indexOfLargestLog = -1;
int lengthOfLargestLog = -1;
// find longest log (logs below logsToMove have already been sorted so we
// don't need to check them again)
for(int i = 0; i < logsToMove; i++)
{
if (inputLogs[i] > lengthOfLargestLog)
{
indexOfLargestLog = i;
lengthOfLargestLog = inputLogs[i];
}
}
// now we know the largest log. Move it to the bottom of what we are currently
// working on
MoveLog(inputLogs, indexOfLargestLog, logsToMove - 1);
logsToMove--;
}
}
// the algorithm I'm using to move a log is:
// 1. get it to the top of the stack
// 2. flip everything so it is where you want it
// To get it to the top of the stack, you can just flip everything up to where it is.
// So two flips to get a log to where you want. This also doesn't disturb anything
// underneath indexToMoveTo.
static void MoveLog(int[] inputLogs, int indexOfLogToMove, int indexToMoveTo)
{
// get to top of stack
Array.Reverse(inputLogs, 0, indexOfLogToMove + 1);
// now flip it to the index we want to move it to
Array.Reverse(inputLogs, 0, indexToMoveTo + 1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment