• Home
  • About
  • Contact
  • ado.net
  • angular
  • c#.net
  • design patterns
  • linq
  • mvc
  • .net core
    • .Net Core MVC
    • Blazor Tutorials
  • sql
  • web api
  • dotnet
    • SOLID Principles
    • Entity Framework
    • C#.NET Programs and Algorithms
  • Others
    • C# Interview Questions
    • SQL Server Questions
    • ASP.NET Questions
    • MVC Questions
    • Web API Questions
    • .Net Core Questions
    • Data Structures and Algorithms

Thursday, August 10, 2017

C# Programming Examples on Sorting

 Abhishek Tomer     August 10, 2017     C#, Programming, Programs     2 comments   

Today i am going to tell you some of the Sorting programming questions in C#.

Q1- Write a C# program to perform Selection sort.
Ans: Selection sort is an algorithm of sorting an array where it loop from the start of the loop, and check through other elements to find the minimum value. After the end of the first iteration, the minimum value is swapped with the current element. The iteration then continues from the 2nd element and so on.

Code:
int array_size = 10;
int[] array = new int[10] { 100, 75, 35, 40, 45, 60, 80, 55, 90, 65 };
Console.WriteLine("The Array Before Selection Sort is: ");
for (int i = 0; i < array_size; i++)
{
    Console.Write("\t" + array[i]);
}
int tmp, min_key;
for (int j = 0; j < array_size - 1; j++)
{
   min_key = j;
   for (int k = j + 1; k < array_size; k++)
   {
      if (array[k] < array[min_key])
       {
          min_key = k;
        }
    }
    tmp = array[min_key];
    array[min_key] = array[j];
    array[j] = tmp;
}
Console.WriteLine("\n" + "The Array After Selection Sort is: ");
for (int i = 0; i < 10; i++)
{
    Console.Write("\t" + array[i]);
}
Console.ReadLine();

Output:
The Array Before Selection Sort is:
        100     75      35      40      45      60      80      55      90      65
The Array After Selection Sort is:
        35      40      45      55      60      65      75      80      90      100


Selection Sort program in C#
Selection Sort in C#
Q2- Write a C# program to perform Bubble sort.
Ans: bubble sort changes the position of numbers or changing an unordered sequence into an ordered sequence.

Code:
int[] numbers = { 50, 25, 20, 22, 35 };
Console.WriteLine("The Array Before Bubble Sort is: ");
for (int i = 0; i < numbers.Length; i++)
{
    Console.Write("\t" + numbers[i]);
}            
bool swapped;
do
{
   swapped = false;
   for (int i = 0; i < numbers.Length - 1; i++)
   {
      if (numbers[i] > numbers[i + 1])
      {
          int temp = numbers[i + 1];
          numbers[i + 1] = numbers[i];
          numbers[i] = temp;
          swapped = true;
       }
  }
} while (swapped == true);
Console.WriteLine("\n" + "The Array After Bubble Sort is: ");
for (int i = 0; i < numbers.Length; i++)
{
    Console.Write("\t" + numbers[i]);
}

Console.ReadLine();

Output:
The Array Before Bubble Sort is:
        50      25      20      22      35
The Array After Bubble Sort is:

        20      22      25      35      50
Bubble Sort program in C#
Bubble Sort in C#
Q3- Write a C# program to perform Radix sort.
Ans: Radix Sort is a non-comparative integer sorting algorithm that sorts data with integer keys by grouping keys by the individual digits which share the same significant position and value

Code:
class Program
    {
        private int[] data;
        private IList> digits = new List>();
        private int maxLength = 0;
        public Program()
        {
            for (int i = 0; i < 10; i++)
            {
                digits.Add(new List());
            }
            Console.Write("Enter the Number of Records : ");
            int count = int.Parse(Console.ReadLine());
            data = new int[count];
            for (int i = 0; i < count; i++)
            {
                Console.Write("Enter Record {0} : ", i + 1);
                data[i] = int.Parse(Console.ReadLine());
                if (maxLength < data[i].ToString().Length)
                    maxLength = data[i].ToString().Length;
            }
        }
        public void RadixSort()
        {
            for (int i = 0; i < maxLength; i++)
            {
                for (int j = 0; j < data.Length; j++)
                {
                    int digit = (int)((data[j] % Math.Pow(10, i + 1)) / Math.Pow(10, i));
                    digits[digit].Add(data[j]);
                }
                int index = 0;
                for (int k = 0; k < digits.Count; k++)
                {
                    IList selDigit = digits[k];
                    for (int l = 0; l < selDigit.Count; l++)
                    {
                        data[index++] = selDigit[l];
                    }
                }
                ClearDigits();
            }
            printSortedData();
        }
        private void ClearDigits()
        {
            for (int k = 0; k < digits.Count; k++)
            {
                digits[k].Clear();
            }
        }
        public void printSortedData()
        {
            Console.WriteLine("The Sorted Numbers are : ");
            for (int i = 0; i < data.Length; i++)
            {
                Console.WriteLine("\t" + data[i]);
            }
        }
        static void Main(string[] args)
        {
            new Program().RadixSort();
            Console.ReadLine();
        }
    }

Output:
Enter the Number of Records : 5
Enter Record 1 : 25
Enter Record 2 : 26
Enter Record 3 : 24
Enter Record 4 : 23
Enter Record 5 : 22
The Sorted Numbers are :
        22
        23
        24
        25

        26
Radix Sort program in C#
Radix Sort in C#
Q4- Write a C# program to perform Heap sort.
Ans: Heap sort first removes the topmost item (the largest) and replace it with the rightmost leaf. The topmost item is stored in an array and Re-establish the heap.this is done until there are no more items left in the heap.

Code:
class Program
    {
        int[] r = { 2, 5, 1, 10, 6, 9, 3, 7, 4, 8 };
        public void hsort()
        {
            int i, t;
            for (i = 5; i >= 0; i--)
            {
                adjust(i, 9);
            }
            for (i = 8; i >= 0; i--)
            {
                t = r[i + 1];
                r[i + 1] = r[0];
                r[0] = t;
                adjust(0, i);
            }
        }
        private void adjust(int i, int n)
        {
            int t, j;
            try
            {
                t = r[i];
                j = 2 * i;
                while (j <= n)
                {
                    if (j < n && r[j] < r[j + 1])
                        j++;
                    if (t >= r[j])
                        break;
                    r[j / 2] = r[j];
                    j *= 2;
                }
                r[j / 2] = t;
            }
            catch (IndexOutOfRangeException e)
            {
                Console.WriteLine("Array Out of Bounds ", e);
            }
        }
        public void print()
        {
            for (int i = 0; i < 10; i++)
            {
                Console.Write("\t"+ r[i]);
            }
        }
        public static void Main()
        {
            Program obj = new Program();
            Console.WriteLine("Elements Before sorting : ");
            obj.print();
            obj.hsort();
            Console.WriteLine("\nElements After sorting : ");
            obj.print();
            Console.ReadLine();
        }
    }

Output:
Elements Before sorting :
        2       5       1       10      6       9       3       7       4       8
Elements After sorting :

        1       2       3       4       5       6       7       8       9       10
Heap Sort program in C#
Heap Sort in C#
Q5- Write a C# program to perform Insertion sort.
Ans: Insertion sort takes an element from the list and places it in the correct location in the list. This process is repeated until there are no more unsorted items in the list.

Code:
static void Main(string[] args)
{
  int[] arr = new int[5] { 83, 12, 3, 34, 60 };
  int i;
  Console.WriteLine("The Array is :");
  for (i = 0; i < 5; i++)
  {
     Console.Write("\t" + arr[i]);
  }
  insertsort(arr, 5);
  Console.WriteLine("\nThe Sorted Array is :");
  for (i = 0; i < 5; i++)
     Console.Write("\t" + arr[i]);
 Console.ReadLine();
}
static void insertsort(int[] data, int n)
{
   int i, j;
   for (i = 1; i < n; i++)
   {
     int item = data[i];
     int ins = 0;
     for (j = i - 1; j >= 0 && ins != 1;)
     {
        if (item < data[j])
        {
         data[j + 1] = data[j];
          j--;
         data[j + 1] = item;
       }
       else ins = 1;
     }
  }
}

Output:
The Array is :
        83      12      3       34      60
The Sorted Array is :

        3       12      34      60      83
Insertion Sort program in C#
Insertion Sort in C#
Q6- Write a C# program to perform Merge sort.
Ans: A merge sort is a sorting algorithm with complexity of O(nlogn). It is used for sorting numbers, structure, files.

Code:
static public void mergemethod(int[] numbers, int left, int mid, int right)
{
  int[] temp = new int[25];
  int i, left_end, num_elements, tmp_pos;
  left_end = (mid - 1);
  tmp_pos = left;
  num_elements = (right - left + 1);
  while ((left <= left_end) && (mid <= right))
  {
    if (numbers[left] <= numbers[mid])
         temp[tmp_pos++] = numbers[left++];
    else
         temp[tmp_pos++] = numbers[mid++];
  }
  while (left <= left_end)
        temp[tmp_pos++] = numbers[left++];
  while (mid <= right)
        temp[tmp_pos++] = numbers[mid++];
  for (i = 0; i < num_elements; i++)
   {
   numbers[right] = temp[right];
   right--;
   }
}
static public void sortmethod(int[] numbers, int left, int right)
{
  int mid;
  if (right > left)
  {
    mid = (right + left) / 2;
    sortmethod(numbers, left, mid);
    sortmethod(numbers, (mid + 1), right);
    mergemethod(numbers, left, (mid + 1), right);
  }
}
static void Main(string[] args)
{
   int[] numbers = { 3, 8, 7, 5, 2, 1, 9, 6, 4 };
   int len = 9;
   Console.WriteLine("Numbers Before MergeSort :");
   for (int i = 0; i < 9; i++)
        Console.Write("\t" + numbers[i]);
   Console.WriteLine("\nNumbers After MergeSort :");
   sortmethod(numbers, 0, len - 1);
   for (int i = 0; i < 9; i++)
       Console.Write("\t" + numbers[i]);
   Console.Read();
}

Output:
Numbers Before MergeSort :
        3       8       7       5       2       1       9       6       4
Numbers After MergeSort :

        1       2       3       4       5       6       7       8       9
Merge Sort program in C#
Merge Sort in C#
Q7- Write a C# program to perform Quick sort.
Ans: Quicksort is a divide and conquer algorithm. Here Quicksort first divides a large array into two smaller sub-array: the low elements and the high elements. Quicksort can then recursively sort the sub-arrays.

Code:
class Program
    {
        private int[] array = new int[20];
        private int len;
        public void QuickSort()
        {
            sort(0, len - 1);
        }
        public void sort(int left, int right)
        {
            int pivot, leftend, rightend;
            leftend = left;
            rightend = right;
            pivot = array[left];
            while (left < right)
            {
                while ((array[right] >= pivot) && (left < right))
                {
                    right--;
                }

                if (left != right)
                {
                    array[left] = array[right];
                    left++;
                }

                while ((array[left] <= pivot) && (left < right))
                {
                    left++;
                }

                if (left != right)
                {
                    array[right] = array[left];
                    right--;
                }
            }
            array[left] = pivot;
            pivot = left;
            left = leftend;
            right = rightend;
            if (left < pivot)
            {
                sort(left, pivot - 1);
            }
            if (right > pivot)
            {
                sort(pivot + 1, right);
            }
        }
        public static void Main()
        {
            Program q_Sort = new Program();
            int[] array = { 4, 3, 1, 4, 6, 7, 5, 4, 32, 5, 26, 187, 8 };
            Console.WriteLine("Numbers Before Quick Sort:");
            for (int j = 0; j < array.Length; j++)
            {
                Console.Write("\t" + array[j]);
            }
            q_Sort.array = array;
            q_Sort.len = q_Sort.array.Length;
            q_Sort.QuickSort();
            Console.WriteLine("\nNumbers After Quick Sort:");
            for (int j = 0; j < q_Sort.len; j++)
            {
                Console.Write("\t" + q_Sort.array[j]);
            }
            Console.ReadKey();
        }
    }

Output:
Numbers Before Quick Sort:
        4       3       1       4       6       7       5       4       32      5       26      187     8
Numbers After Quick Sort:

        1       3       4       4       4       5       5       6       7       8       26      32      187
Quick Sort program in C#
Quick Sort in C#
Summary:
So, Guys this was all about the sorting programming questions in C#.
I hope you have enjoyed this post.
Please share this post with your friends and colleagues to help them clearing the interview.

For any queries please post a comment below.

Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

2 comments:

  1. UnknownAugust 12, 2017 at 10:52 PM

    Nice Examples

    ReplyDelete
    Replies
    1. Abhishek TomerAugust 12, 2017 at 10:54 PM

      Thanks Mate :)

      Delete
      Replies
        Reply
    2. Reply
Add comment
Load more...

If you like this website, please share with your friends on Facebook, Twitter, LinkedIn.

Join us on Telegram

Loved Our Blog Posts? Subscribe To Get Updates Directly To Your Inbox

Like us on Facebook

Popular Posts

  • What is Dependency Injection(DI)
    Hi friends! Today we are going to learn about Dependency Injection and in our last session we have come across Static classes and where it s...
  • Navigation Menus in ASP.NET Core
    In this article, I am going to discuss how to create Responsive Navigation Menus in ASP.NET Core Application using bootstrap and JQuery. P...
  • What is Abstract Class and When we should use Abstract Class
    Hi friends! In our previous sessions we have seen  Difference Between Class and Struct . And in our last session  we learnt Usability of Sec...
  • ASP.NET State Management
    State management is a technique or way to maintain / store the state of an Asp.Net controls, web page information, object/data, and user in ...
  • HTTP Client Message Handler in Web API
    In this article, I am going to discuss HTTP Client Message Handler in Web API with real-time examples. As we already discussed in HTTP Mes...
  • ASP.NET Web API Basic Authentication
    In this article, I am going to discuss how to implement the ASP.NET Web API Basic Authentication step by step with an example. Please read...
  • Anonymous Types in C#
    Hi friends! Today we are going to learn about Anonymous Types in C#. Let's start with the Introduction Anonymous is a type that does...

Blog Archive

Contact Form

Name

Email *

Message *

Tags

.Net .Net Core .Net Core MVC Algorithm Angular Anonymous Types Asp.Net Asp.Net MVC Blazor C# Data Structure Database Design Patterns Entity Framework Entity Framework Core Filters Interview Question Management Studio Programming Programs SQL Server SSMS Web API

Copyright © C# Techtics | All Right Reserved.

Protected by Copyscape