Insertion Sort - Part 1

  • + 0 comments

    My C# solution

    class Result {

    /*
     * Complete the 'insertionSort1' function below.
     *
     * The function accepts following parameters:
     *  1. INTEGER n
     *  2. INTEGER_ARRAY arr
     */
    
    public static void insertionSort1(int n, List<int> arr)
    {
    
       int lastIndex = arr[n - 1];
        if (lastIndex > arr[n - 2])
        {
            for (int i = 0; i < n - 1; i++)
            {
                Console.Write(arr[i] + " ");
            }
        }
        else
        {
            arr[n - 1] = arr[n - 2];
            for (int i = 0; i < n; i++)
            {
                Console.Write(arr[i] + " ");
            }
    
            for (int j = n - 3; j >= 0; j--)
            {
                Console.WriteLine();
                if (lastIndex < arr[j])
                {
                    arr[j + 1] = arr[j];
                    for (int k = 0; k < n; k++)
                    {
                        Console.Write(arr[k] + " ");
                    }
                    continue;
                }
                else
                {
                    arr[j + 1] = lastIndex;
                    for (int k = 0; k < n; k++)
                    {
                        Console.Write(arr[k] + " ");
    
                    }
                }
                break;
            }
        }
    
    }
    

    }

    class Solution { public static void Main(string[] args) { int n = Convert.ToInt32(Console.ReadLine().Trim());

        List<int> arr = Console.ReadLine().TrimEnd().Split(' ').ToList().Select(arrTemp => Convert.ToInt32(arrTemp)).ToList();
    
        Result.insertionSort1(n, arr);
    }
    

    }