C#

sort array without using inbuilt function


sort array


namespace Demo
{
    class Program
    {
      
        static void Main(string[] args)
        {
            //define array with even number
            int[] A = { 12, 13, 14, 2, 34, 7, 6, 5, 3, 1 };
            //declare a temp variable to hold value
            int temp;
            //get mid length of array for sorting first half array in descending and
            //second half for ascending order
            int midOfArray = A.Length / 2;
            //run loop for sorting in descending order of array element
            for (int i = 0; i < midOfArray; i++)
            {
                //compare value of array and arrange element
                for (int j = i + 1; j < midOfArray; j++)
                {
                    if (A[i] < A[j])
                    {
                        temp = A[i];
                        A[i] = A[j];
                        A[j] = temp;
                    }
                }
            }
            //second loop for ascending second part in ascending order
            for (int i = midOfArray; i < A.Length; i++)
            {
                for (int j = i + 1; j < A.Length; j++)
                {
                    if (A[i] > A[j])
                    {
                        temp = A[i];
                        A[i] = A[j];
                        A[j] = temp;
                    }
                }
            }
//the result will be display using foreach loop
            foreach (var item in A)
            {
                Console.WriteLine(item);
            }

            Console.ReadLine();
        }


    }
}


sort array

The output is :- 

sort array




No comments:

Post a Comment