In computer science, Sorting describes organizing in an ordered sequence. Numerous applications frequently use sorting, and effective algorithms to carry it out have been created. The most frequent applications for sorted sequences are efficient lookup, search, and merge of sequences and processing data in a predetermined order. Shuffling is the antithesis of Sorting, which is rearranging a series of things in an arbitrary or meaningless order.
In this "Sorting Algorithms in C#," you will explore the most important technical and practical aspects of typecasting and working around various types of variables.
What Is Sorting?
Sorting is the technique of putting the items of a collection in a certain order in C#. An array, a list, or other data set can be considered a collection. The collection may contain items of both simple and complex kinds. A simple type can be an array of integers, texts, floating-point values, and so on.
A complex type might be a collection of objects of user-defined kinds like Employees, students, etc. Complex types are frequently nested, meaning the objects may have several characteristics. C# includes built-in methods for sorting collections. C# Sort() may sort an Array, List, or any Generic Collection depending on the Comparer.
Now that we understand what Sorting is, let's discuss some basic Sorting methods.
Basic Sorting Methods
There are various Sorting methods available to sort an Array aside from our Sorting Algorithms.
We'll look at a few of them now.
-
Sort() Function
Code:
using System;
namespace Sort_method
{
class Program
{
static void Main(string[] args)
{
// declaring and initializing the array
int[] arr = new int[] {16, 29, 6, 17, 35, 19};
Console.WriteLine("Unsorted Array: ");
foreach(int value in arr)
{
Console.Write(value + " ");
}
// Sort array in ascending order.
Array.Sort(arr);
Console.WriteLine("\nUnsorted Array: ");
// print all elements of the array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
}
-
CompareTo() Function
Code:
using System;
namespace Compareto_method
{
class Program
{
static void Main(string[] args)
{
// declaring and initializing the array
int[] arr = new int[] {16, 29, 6, 17, 35, 19};
Console.WriteLine("Unsorted Array:");
foreach(int value in arr)
{
Console.Write(value + " ");
}
// Sort the arr from first to Last.
// compare every element to each other
Array.Sort<int>(arr, new Comparison<int>(
(i1, i2) => i1.CompareTo(i2)));
Console.WriteLine("\nSorted Array:");
// print all elements of the array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
}
-
Using Delegates Method:
Code:
using System;
namespace Using_Delegates
{
class Program
{
static void Main(string[] args)
{
// declaring and initializing the array
int[] arr = new int[] {16, 29, 6, 17, 35, 19};
Console.WriteLine("Unsorted Array: ");
foreach(int value in arr)
{
Console.Write(value + " ");
}
// Sort the arr from first to last
Array.Sort<int>(arr, delegate(int m, int n)
{ return m - n; });
Console.WriteLine("\n\nSorted Array: ");
// print all elements of the array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
}
-
Using Linq Library Functions
Code:
using System;
using System.Linq;
namespace Using_LINQ
{
class Program
{
static void Main(string[] args)
{
// declaring and initializing the
// array with six positive number
int[] arr = new int[] {16, 29, 6, 17, 35, 19};
Console.WriteLine("Unsorted Array:");
foreach(int value in arr)
{
Console.Write(value + " ");
}
// Sort the arr in Increasing order
// and return an array
arr = arr.OrderBy(c => c).ToArray();
Console.WriteLine("\n\nSorted Array:");
// print all elements of the array
foreach(int value in arr)
{
Console.Write(value + " ");
}
}
}
}
-
Iterative Method
Code:
using System;
namespace Iterative
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] {16, 29, 6, 17, 35, 19};
int temp;
//Print the Unsorted Array
Console.WriteLine("Unsorted Array:");
foreach(int x in arr)
{
Console.Write(x + " ");
}
// traverse 0 to array length
for(int itr1=0; itr1<arr.Length-1;itr1++)
// traverse i+1 to array length
for(int itr2=itr1+1;itr2<arr.Length;itr2++)
// compare array element with all next element
if (arr[itr1] > arr[itr2]) {
temp = arr[itr1];
arr[itr1] = arr[itr2];
arr[itr2] = temp;
}
Console.WriteLine("\n\nSorted Array:");
// print all elements of the array
foreach(int x in arr)
{
Console.Write(x + " ");
}
}
}
}
Now let's check out various Sorting Algorithms.
Sorting Algorithms
We will discuss the Sorting Algorithms given Below and the logic behind them.
Let's discuss each of them in Detail.
Bubble Sort Algorithm
Logic:
We will start with the first two elements and compare them. If the first is bigger than the second, we will switch them. And then, we will move on to the next set of pairs. We will repeat this with the next set of pairs as well.
Once we have reached the end, we will go into the second iteration and repeat the last step.
As you can check the image above, the array is sorted. But our algorithm doesn't know that. So we will go into the third iteration. And let's say if we don't find any swaps, we will declare it to be a sorted array.
Code:
using System;
namespace Bubble_Sort
{
class Program
{
static void bubbleSort(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n - 1; i++)
for (int j = 0; j < n - i - 1; j++)
if (arr[j] > arr[j + 1]) {
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
/* Prints the array */
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver method
public static void Main()
{
int[] arr = { 4, 2, 1, 8, 3};
Console.WriteLine("Unsorted array:");
printArray(arr);
bubbleSort(arr);
Console.WriteLine("\nSorted array:");
printArray(arr);
}
}
}
Insertion Sort Algorithm
Logic:
Let's say we have an array. We will start with traversing the array from index 1 to n-1.
While traversing, we will compare elements in the current index to its predecessor.
If data at the current index is smaller than its predecessor, then we will compare it with the element before that.
Then, We will shift a bigger element to an index up to make space for the swapped element, and then we will iterate the same steps again to sort the complete array.
Code:
using System;
namespace Insertion_Sort
{
class InsertionSort
{
// Function to sort array
// using insertion sort
void sort(int[] arr)
{
int n = arr.Length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
// Move elements of arr[0..i-1],
// that is greater than key,
// to one position ahead of
// their current position
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print
// array of size n
static void printArray(int[] arr)
{
int n = arr.Length;
for (int i = 0; i < n; ++i)
Console.Write(arr[i] + " ");
Console.Write("\n");
}
// Driver Code
public static void Main()
{
int[] arr = { 6, 5, 4, 2, 3 };
Console.WriteLine("Unsorted array:");
printArray(arr);
InsertionSort IS = new InsertionSort();
IS.sort(arr);
Console.WriteLine("\nSorted array:");
printArray(arr);
}
}
}
Selection Sort Algorithm
Logic:
Let's say we have an array. First, we will divide this array into two subarrays: unsorted and sorted Subarray.
Then, we will find the minimum element from the unsorted array and swap it with the leftmost element of this unsorted array. After that, we will add it to the sorted array.
We will keep repeating this process until no elements are left on the unsorted array.
Code:
using System;
namespace Selection_Sort
{
class Program
{
static void sort(int []arr)
{
int n = arr.Length;
// One by one move boundary of unsorted Subarray
for (int i = 0; i < n - 1; i++)
{
// Find the minimum element in the unsorted array
int min_idx = i;
for (int j = i + 1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}
// Prints the array
static void printArray(int []arr)
{
int n = arr.Length;
for (int i=0; i<n; ++i)
Console.Write(arr[i]+" ");
Console.WriteLine();
}
// Driver code
public static void Main()
{
int []arr = { 4, 2, 1, 8, 3 };
Console.WriteLine("Unsorted array:");
printArray(arr);
sort(arr);
Console.WriteLine("\nSorted array:");
printArray(arr);
}
}
}
Quick Sort Algorithm
Logic:
Let's say we have an array. First, We have to select a pivot. We can select the first element, the last or median, or any random element as pivots.
This pivot will dissect the array in two sub-arrays then we will shift all smaller elements from the pivot element to the left.
Then we will again apply the same operation for the left Subarray and take pivot as we did for the main array.
We will perform the same for the right Subarray as well.
Code:
using System;
namespace Quick_Sort
{
class Program
{
// A utility function to swap two elements
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
/*
This function uses the last element as a pivot and arranges all other elements so that all smaller elements are placed to the left of the pivot and all larger elements are placed to the right of the pivot in a sorted array.
*/
static int partition(int[] arr, int low, int high)
{
// pivot
int pivot = arr[high];
// Index of smaller elements and
// indicates the right position
// of pivot found so far
int i = (low - 1);
for (int j = low; j <= high - 1; j++)
{
// If the current element is smaller
// than the pivot
if (arr[j] < pivot)
{
// Increment index of
// smaller element
i++;
swap(arr, i, j);
}
}
swap(arr, i + 1, high);
return (i + 1);
}
/* The main function that implements QuickSort
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index
*/
static void quickSort(int[] arr, int low, int high)
{
if (low < high)
{
// pi is partitioning index, arr[p]
// is now at right place
int pi = partition(arr, low, high);
// Separately sort elements before
// partition and after partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
// Function to print an array
static void printArray(int[] arr, int size)
{
for (int i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver Code
public static void Main()
{
int[] arr = { 6, 9, 5, 2, 3 };
int n = arr.Length;
Console.Write("Unsorted array: ");
printArray(arr, n);
quickSort(arr, 0, n - 1);
Console.Write("\nSorted array: ");
printArray(arr, n);
}
}}
You have a good command of Sorting Algorithms' technical and theoretical aspects in C#. Check out what's next in your journey to master C# programming.
Master front-end and back-end technologies and advanced aspects in our Post Graduate Program in Full Stack Web Development. Unleash your career as an expert full stack developer. Get in touch with us NOW!
Next Steps
You can start with "Boxing and Unboxing in C#" as your next Chapter in your path to conquering C# Programming. A value type can be "boxed" into any object or interface type that it implements. The process of changing an object type parameter into a value type parameter is known as unboxing. If you want to unbox an object into a unique data type than its original, you have to double typecast.
If you want to master skills relevant to today's economy, you should enroll at Simplilearn, the world's most popular online Bootcamp for doing just that. Topics like data science and digital marketing are covered in our online courses.
You've found the appropriate location to hone your software development skills and prepare for an industry career. Software Development courses from both the Indian Institute of Technology (IIT) in Kanpur and the California Institute of Technology (CaltechCenter ) 's for Technology Management and Education (CTME) are available through Simplilearn. Data structures and algorithms, as well as more advanced subjects like Competitive Programming, are covered in these classes. As a software engineer, you'll have experience working with various data structures, such as trees, graphs, and queues.
If you have questions about this "Sorting Algorithm in C#" lesson, feel free to post them in the comments section. Good luck with a productive educational experience!