Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save schauhan232/860a6abf266120fcf31dd6bb2746e22d to your computer and use it in GitHub Desktop.
Save schauhan232/860a6abf266120fcf31dd6bb2746e22d to your computer and use it in GitHub Desktop.
Create next smallest number from the same array element
class Program
{
public static void Main(string[] args)
{
var matrix = new int[] { 2, 5, 8, 7, 6, 1 };
var loopLength = matrix.Length - 1;
var firstSmallElementIndex = -1;
//1. Find the index where there's small element on left hand side
while (loopLength >= 0)
{
if (loopLength - 1 <= 0)
break;
if (matrix[loopLength] > matrix[loopLength - 1])
{
firstSmallElementIndex = loopLength;
break;
}
loopLength--;
}
//2. From First found small element, start first small element in right hand side
loopLength = matrix.Length - 1;
var startIndex = firstSmallElementIndex + 1;
var smallestElementOnRightSideIndex = -1;
var smallestElementOnRightSide = matrix[startIndex];
while (startIndex <= loopLength)
{
if (smallestElementOnRightSide > matrix[startIndex])
{
smallestElementOnRightSide = matrix[startIndex];
smallestElementOnRightSideIndex = startIndex;
}
startIndex++;
}
//3. Swap Element
SwapElement(matrix, firstSmallElementIndex, smallestElementOnRightSideIndex);
//4. Sort Element
Array.Sort(matrix, firstSmallElementIndex, loopLength - firstSmallElementIndex);
Console.WriteLine($"Solution: {string.Join(",", matrix)}");
Console.Read();
}
private static void SwapElement(int[] matrix, int start, int end)
{
var a = matrix[start];
matrix[start] = matrix[end];
matrix[end] = a;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment