You are on page 1of 16

Sample Programs in Sorting Algorithm

Bubble Sort

using System;
namespace BubbleSort {
class MySort {
static void Main(string[] args) {
int[] arr = { 78, 55, 45, 98, 13 };
int temp;
for (int j = 0; j <= arr.Length - 2; j++) {
for (int i = 0; i <= arr.Length - 2; i++) {
if (arr[i] > arr[i + 1]) {
temp= arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = temp;
}
}
}
Console.WriteLine("Sorted:");
foreach (int p in arr)
Console.Write(p + " ");
Console.Read();
}
}
}
Output

Follow the below steps to solve the problem:


 Run a nested for loop to traverse the input array using two
variables i and j, such that 0 ≤ i < n-1 and 0 ≤ j < n-i-1
 If arr[j] is greater than arr[j+1] then swap these adjacent elements,
else move on
 Print the sorted array

// C# program for implementation


// of Bubble Sort
using System;

class GFG {
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 = { 5, 1, 4, 2, 8};
bubbleSort(arr);
Console.WriteLine("Sorted array");
printArray(arr);
}
}

// This code is contributed by Sam007

Output
Sorted array:
1 2 4 5 8
Time Complexity: O(N2)
Auxiliary Space: O(1)

https://www.geeksforgeeks.org/bubble-sort/

Description of the bubble sort


algorithm
The algorithm consists in cyclic passes through the array, for each pass the
elements of the array are compared in pairs and, if their order is not correct,
then an exchange is carried out. Array traversal is repeated until the array is
ordered.

Implementing bubble sort


using System;

class program
{
// elements exchange method
static void Swap(ref int e1, ref int e2)
{
var temp = e1;
e1 = e2;
e2 = temp;
}

// sort by bubble
static int[] BubbleSort(int[] array)
{
var len = array.Length;
for (var i = 1; i < len; i++)
{
for (var j = 0; j < len - i; j++)
{
if (array[j] > array[j + 1])
{
Swap(ref array[j], ref array[j + 1]);
}
}
}

return array;
}

static void Main(string[] args)


{
Console.WriteLine("Bubble Sort");
Console.Write("Enter the elements of the
array:");
var parts = Console.ReadLine().Split(new[] { "",
",", ";" }, StringSplitOptions.RemoveEmptyEntries);
var array = new int[parts.Length];
for (int i = 0; i < parts.Length; i++)
{
array[i] = Convert.ToInt32(parts[i]);
}

Console.WriteLine("Sorted array: {0}",


string.Join(",", BubbleSort(array)));

Console.ReadLine();
}
}
https://programm.top/en/c-sharp/algorithm/array-sort/bubble-sort/

Merge Sort is a sorting algorithm that uses the divide and conquer method. It divides the array
into two parts and then calls itself for each of these two parts. This process is continued until the
array is sorted.
A program that demonstrates merge sort in C# is given as follows −
using System;
namespace QuickSortDemo {
class Example {
static public void merge(int[] arr, int p, int q, int r) {
int i, j, k;
int n1 = q - p + 1;
int n2 = r - q;
int[] L = new int[n1];
int[] R = new int[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[p + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[q + 1 + j];
}
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
static public void mergeSort(int[] arr, int p, int r) {
if (p < r) {
int q = (p + r) / 2;
mergeSort(arr, p, q);
mergeSort(arr, q + 1, r);
merge(arr, p, q, r);
}
}
static void Main(string[] args) {
int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100};
int n = 10, i;
Console.WriteLine("Merge Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
mergeSort(arr, 0, n-1);
Console.Write("
Sorted Array is: ");
for (i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
}
}
}

Output
The output of the above program is as follows.
Merge Sort
Initial array is: 76 89 23 1 55 78 99 12 65 100
Sorted Array is: 1 12 23 55 65 76 78 89 99 100
Now let us understand the above program.
In the main() function, first the initial array is displayed. Then, the function mergeSort() is
called to perform merge sort on the array. The code snippet for this is given as follows.
int[] arr = {76, 89, 23, 1, 55, 78, 99, 12, 65, 100};
int n = 10, i;
Console.WriteLine("Merge Sort");
Console.Write("Initial array is: ");
for (i = 0; i < n; i++) {
Console.Write(arr[i] + " ");
}
mergeSort(arr, 0, n-1);
In the function mergeSort(), q is calculated as the mid point of the array. Then mergeSort() is
called on both the sub-arrays created. Finally, merge() is called that merges these sub-arrays.
The code snippet for this is given as follows.
if (p < r) {
int q = (p + r) / 2;
mergeSort(arr, p, q);
mergeSort(arr, q + 1, r);
merge(arr, p, q, r);
}
In the function merge(), two sorted subarrays are provided. This function basically merges these
subarrays into a single array in such a manner that the resultant array is also sorted. The code
snippet for this is given as follows.
int i, j, k;
int n1 = q - p + 1;
int n2 = r - q;
int[] L = new int[n1];
int[] R = new int[n2];
for (i = 0; i < n1; i++) {
L[i] = arr[p + i];
}
for (j = 0; j < n2; j++) {
R[j] = arr[q + 1 + j];
}
i = 0;
j = 0;
k = p;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
Merge Sort

Algorithm:
step 1: start
step 2: declare array and left, right, mid variable
step 3: perform merge function.
if left > right
return
mid= (left+right)/2
mergesort(array, left, mid)
mergesort(array, mid+1, right)
merge(array, left, mid, right)
step 4: Stop
Follow the steps below to solve the problem:
MergeSort(arr[], l, r)
If r > l
 Find the middle point to divide the array into two halves:
 middle m = l + (r – l)/2
 Call mergeSort for first half:
 Call mergeSort(arr, l, m)
 Call mergeSort for second half:
 Call mergeSort(arr, m + 1, r)
 Merge the two halves sorted in steps 2 and 3:
 Call merge(arr, l, m, r)
Below is the implementation of the above approach:

// C# program for Merge Sort


using System;
class MergeSort {

// Merges two subarrays of []arr.


// First subarray is arr[l..m]
// Second subarray is arr[m+1..r]
void merge(int[] arr, int l, int m, int r)
{
// Find sizes of two
// subarrays to be merged
int n1 = m - l + 1;
int n2 = r - m;

// Create temp arrays


int[] L = new int[n1];
int[] R = new int[n2];
int i, j;

// Copy data to temp arrays


for (i = 0; i < n1; ++i)
L[i] = arr[l + i];
for (j = 0; j < n2; ++j)
R[j] = arr[m + 1 + j];

// Merge the temp arrays

// Initial indexes of first


// and second subarrays
i = 0;
j = 0;

// Initial index of merged


// subarray array
int k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
}
else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy remaining elements


// of L[] if any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
// Copy remaining elements
// of R[] if any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}

// Main function that


// sorts arr[l..r] using
// merge()
void sort(int[] arr, int l, int r)
{
if (l < r) {
// Find the middle
// point
int m = l + (r - l) / 2;

// Sort first and


// second halves
sort(arr, l, m);
sort(arr, m + 1, r);

// Merge the sorted halves


merge(arr, l, m, r);
}
}

// 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.WriteLine();
}

// Driver code
public static void Main(String[] args)
{
int[] arr = { 12, 11, 13, 5, 6, 7 };
Console.WriteLine("Given Array");
printArray(arr);
MergeSort ob = new MergeSort();
ob.sort(arr, 0, arr.Length - 1);
Console.WriteLine("\nSorted array");
printArray(arr);
}
}

// This code is contributed by Princi Singh

Output
Given array is
12 11 13 5 6 7
Sorted array is
5 6 7 11 12 13
Time Complexity: O(N log(N)), Sorting arrays on different machines. Merge
Sort is a recursive algorithm and time complexity can be expressed as following
recurrence relation.
T(n) = 2T(n/2) + θ(n)
The above recurrence can be solved either using the Recurrence Tree method
or the Master method. It falls in case II of the Master Method and the solution of
the recurrence is θ(Nlog(N)). The time complexity of Merge Sort isθ(Nlog(N)) in
all 3 cases (worst, average, and best) as merge sort always divides the array
into two halves and takes linear time to merge two halves.
Auxiliary Space: O(n), In merge sort all elements are copied into an auxiliary
array. So N auxiliary space is required for merge sort.

Selection Sort Algorithm

After N (size of array) iteration we will get sorted array.

Flowchart of the Selection Sort:


How selection sort works?
Lets consider the following array as an example: arr[] = {64, 25, 12, 22, 11}
First pass:
 For the first position in the sorted array, the whole array is traversed
from index 0 to 4 sequentially. The first position where 64 is stored
presently, after traversing whole array it is clear that 11 is the lowest
value.

64 25 12 22 11

 Thus, replace 64 with 11. After one iteration 11, which happens to be
the least value in the array, tends to appear in the first position of the
sorted list.

11 25 12 22 64

Second Pass:
 For the second position, where 25 is present, again traverse the rest
of the array in a sequential manner.

11 25 12 22 64

 After traversing, we found that 12 is the second lowest value in the


array and it should appear at the second place in the array, thus swap
these values.

11 12 25 22 64

Third Pass:
 Now, for third place, where 25 is present again traverse the rest of the
array and find the third least value present in the array.

11 12 25 22 64
 While traversing, 22 came out to be the third least value and it should
appear at the third place in the array, thus swap 22 with element
present at third position.

11 12 22 25 64

Fourth pass:
 Similarly, for fourth position traverse the rest of the array and find the
fourth least element in the array
 As 25 is the 4th lowest value hence, it will place at the fourth position.

11 12 22 25 64

Fifth Pass:
 At last the largest value present in the array automatically get placed
at the last position in the array
 The resulted array is the sorted array.

11 12 22 25 64

Follow the below steps to solve the problem:


 Initialize minimum value(min_idx) to location 0.
 Traverse the array to find the minimum element in the array.
 While traversing if any element smaller than min_idx is found then
swap both the values.
 Then, increment min_idx to point to the next element.
 Repeat until the array is sorted.

// C# program for implementation


// of Selection Sort
using System;

class GFG
{
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 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 = {64,25,12,22,11};
sort(arr);
Console.WriteLine("Sorted array");
printArray(arr);
}

}
// This code is contributed by Sam007

Output
Sorted array:
11 12 22 25 64

Complexity Analysis of Selection Sort:


Time Complexity: The time complexity of Selection Sort is O(N 2) as there are
two nested loops:
 One loop to select an element of Array one by one = O(N)
 Another loop to compare that element with every other Array element
= O(N)
Therefore overall complexity = O(N) * O(N) = O(N*N) = O(N 2)
Auxiliary Space: O(1) as the only extra memory used is for temporary
variables while swapping two values in Array. The selection sort never makes
more than O(N) swaps and can be useful when memory write is a costly
operation.

You might also like