C# array sorting | Sorting numbers in C#

using System;

namespace ClassRoomSamples
{
    class Demo05ArraySorting
    {
        static void Main(String[] anyname)
        {
            int[] a = new int[10];

            Console.WriteLine("How many numbers needed to sort(Max 10)?");
            int n = int.Parse(Console.ReadLine());

            for (int i = 0; i < n; i++)
            {
                a[i] = int.Parse(Console.ReadLine());
            }

            //Starting with 0 as selected-index and proceeding up to n-1
            for (int SelectedIndex = 0; SelectedIndex < n-1;                                                                     SelectedIndex++)
            {
                //searching if any small value occurring...
                for (int followingIndex=SelectedIndex+1;followingIndex<n;                                                          followingIndex++)
                {
                    //if following position's value is smaller than 
                    //the selected-index value
                    if (a[SelectedIndex] > a[followingIndex])
                    {
                        //then Swap values
                        int backUp = a[SelectedIndex];
                        a[SelectedIndex] = a[followingIndex];
                        a[followingIndex] = backUp;
                    }
                }
            }

            Console.WriteLine("Sorted Array values");
            for (int i = 0; i < n; i++)
            {
                 Console.WriteLine(a[i]);
            }

            Console.ReadKey();
        }
    }
}


Output

How many numbers needed to sort (Max 10)?
6

12
15
10
13
18
17

Sorted Array values
10
12
13
15
17
18

No comments:

Post a Comment