Hackerrank Challenge 3

Insertions Sort

//https://www.hackerrank.com/challenges/insertionsort1

class Program
    {
        static void Main(String[] args)
        {
            int _ar_size;
            _ar_size = Convert.ToInt32(Console.ReadLine());
            int[] _ar = new int[_ar_size];
            String elements = Console.ReadLine();
            String[] split_elements = elements.Split(' ');
            for (int _ar_i = 0; _ar_i < _ar_size; _ar_i++)
            {
                _ar[_ar_i] = Convert.ToInt32(split_elements[_ar_i]);
            }

            insertionSort(_ar);
            Console.ReadLine();

        }
       
        static void insertionSort(int[] ar)
        {
            bool sorted = false;
           
            int rightmost_num = ar[ar.Length-1];
            for (int i = ar.Length-1; i > 0; i--)
            {
                bool IsShift = false;
                if (rightmost_num < ar[i - 1] && sorted == false)
                {
                    ar[i] = ar[i - 1];
                    IsShift = true;
                    //if (i - 1 == 0)
                    //{
                    //    ar[i - 1] = rightmost_num;
                    //    sorted = true;
                       
                    //}

                }

                else if (rightmost_num > ar[i - 1] && sorted==false)
                {
                    ar[i] = rightmost_num;
                    sorted = true;
                    IsShift = true;

               
                }



                if (IsShift == true)
                {

                    for (int j = 0; j < ar.Length; j++)
                    {
                        Console.Write(ar[j] + " ");

                    }
                }
                Console.Write("\n");
               
                }
            if (sorted == false)
            {
                ar[0] = rightmost_num;
                for (int j = 0; j < ar.Length; j++)
                {
                    Console.Write(ar[j] + " ");

                }
            }





        }

         
    }

Comments

Popular posts from this blog

Authentication and Authorization in Web API -Part1

My Gardening Journey 6