How to sort an Array till a particular number – Nagarro Interview Question with Answer

How to sort an Array till a particular number ?

Example : {19,5,7,3,9,6,8,1,2,11}
Enter a number till where you want to sort : 6 ->means {19,5,7,3,9,6,8,1,2,11}
Output : {3,5,6,7,9,19,8,1,2,11}

Nagarro




using System;

namespace Nagarro
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter size of integer array : ");
            int arrLength = Convert.ToInt32(Console.ReadLine());

            Console.WriteLine("Enter values for Array : ");
            int[] arr = new int[arrLength];
            
            ArraySorting(arrLength, arr);
            Console.ReadKey();
        }

        private static void ArraySorting(int arrLength, int[] arr)
        {
            string temparray=null;
            int Index ,temp, num = 0;

            for (int i = 0; i < arrLength; i++)
            {
                arr[i] = Convert.ToInt32(Console.ReadLine());
                temparray = temparray + " " + arr[i]; // Input Array
            }

            Console.Write("Input array : " + temparray); // Input Array
            
            Console.Write(Environment.NewLine + "Enter number upto there you want sort : ");
            num = Convert.ToInt32(Console.ReadLine());

            Index = Array.IndexOf(arr, num);

            //OR If you want to use Array.IndexOf , then uncomment below code 
            //foreach (int i in arr)
            //{
            //    if (i == num)
            //    {
            //        Index++;
            //        break;
            //    }
            //    else
            //        Index++;
            //}

            for (int i = 1; i < arr.Length; i++)
            {
                for (int j = 1; j <= Index; j++)
                {
                    while (arr[j - 1] > arr[j])
                    {
                        temp = arr[j - 1];
                        arr[j - 1] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            temparray = null;
            foreach (int item in arr)
            {
                Console.WriteLine(item);
                temparray = temparray + " " + item; // Output Array
            }

            // Output Array
            Console.Write("Output array : " + temparray);
          
        }
    }
}