During an interview, I was given this Hackerrank question to solve within 15 minutes but at that time I was interested in solving this without performance in my mind. I know a similar question has been asked Hackerrank Insertion Sort - Java and probably a lot in CR.
Problem Statement
Given a sorted list with an unsorted number e in the rightmost cell, can you write some simple code to insert into the array so that it remains sorted?
Print the array every time a value is shifted in the array until the array is fully sorted. The goal of this challenge is to follow the correct order of insertion sort.
Guideline: You can copy the value of to a variable and consider its cell "empty". Since this leaves an extra cell empty on the right, you can shift everything over until can be inserted. This will create a duplicate of each value, but when you reach the right spot, you can replace it with .
Input Format
There will be two lines of input:
Size
- the size of the arrayArr
- the unsorted array of integers
Output Format
On each line, output the entire array every time an item is shifted in it.
Constraints
- 1 ≤ Size ≤ 1000
- -10000 ≤ e ≤ 1000, e E Arr
Sample Input
5
2 4 6 8 3
Sample Output
2 4 6 8 8
2 4 6 6 8
2 4 4 6 8
2 3 4 6 8
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution
{
public static void printArray(int[] array)
{
var b = array.Select((x) => Convert.ToString(x) + " ").Cast<string>();
Console.WriteLine(String.Concat(b));
}
public static void insertionSort(int[] unsortedArray)
{
int unsortedElement = unsortedArray.ElementAt(unsortedArray.Count() - 1);
int i = unsortedArray.Length - 1;
while (i != -1)
{
if (i - 1 != -1)
{
if (unsortedArray[i - 1] > unsortedElement)
{
unsortedArray[i] = unsortedArray[i - 1];
printArray(unsortedArray);
}
else
{
unsortedArray[i] = unsortedElement;
printArray(unsortedArray);
break;
}
}
else
{
unsortedArray[i] = unsortedElement;
printArray(unsortedArray);
break;
}
i--;
}
}
}
Any thoughts on performance, style or shortened code length?