• 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

Sunday, August 16, 2020

Bubble Sort in C#

 Admin     August 16, 2020     C#, Interview Question, Programming, Programs     No comments   

In this article, I am going to discuss the Bubble Sort in C# with Examples. The Bubble sort is a sorting algorithm and used by the many developers in real-time applications. You can use this algorithm with any type of collection such as an array, string, numbers, or characters.

The Bubble Sort Algorithm:
The Bubble Sort Algorithm works on the concept of iterating through the array from the first index to the last index and comparing it with the adjacent elements and then swapping the elements if they appear in the wrong order i.e. if the next element is smaller than the current element, they are swapped.

Pictorial Representation of Bubble Sort:
In order to sort an array, there will be n-1 passes where n is the number of elements in the array. For better understanding please have a look at the following diagram. Let us take an input array such as 8 5 7 3 1.
Bubble Sort in C#

As you can see in the above image we have an integer array with 5 elements such as 8 5 7 3 1.

Iteration1:
The bubble sort starts with the first two elements i.e. 8 and 5. As 5 is smaller than 8, so swap both of them. Now the list is 5 8 7 3 1. Again 7 is less than 8, so swap them which results as 5 7 8 3 1. Now, 3 is less than 8, so swap them which results in the sequence like 5 7 3 8 1. Finally 1 is less than 8, so swap them which concludes the iteration1 as 5 7 3 1 and 8.

Iteration2:
For iteration2 the sequence is 5 7 3 1 and 8. Here, the first 2 elements are 5 and 7. 7 is greater than 5, so no need to swap them. The 7 is compared with 3 and 3 is less than 7, so swap them which results in the sequences as 5 3 7 1 8. Then 1 is less than 7 so swap them which results in the sequence like 5 3 1 7 8.

Iteration3: For the iteration3, the sequence will be 5 3 1 7 8. Here, the first two elements are 5 and 3. 3 is less than 5, so swap them which results in the sequences as 3 5 1 7 and 8. Again 1 is less than 5, so swap them which concludes the iteration3 with the sequences as 3 1 5 7 and 8.

Iteration4:
This is the last iteration. This iteration starts with the sequence as 3 1 5 7 and 8. Here the first two elements are 3 and 1. 1 is less than 3, so swap them which results in the elements in the sorted order as 1 3 5 7 and 8.

Program to implement bubble sort in C#:
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            int[] intArray = new int[5];
            Console.WriteLine("Enter the Array Elements : ");
            for (int i = 0; i < intArray.Length; i++)
            {
                intArray[i] = int.Parse(Console.ReadLine());
            }
            //Sorting the array
            for (int j = 0; j <= intArray.Length - 2; j++)
            {
                //intArray.Length - 2
                for (int i = 0; i <= intArray.Length - 2; i++)
                {
                    count = count + 1;
                    if (intArray[i] > intArray[i + 1])
                    {
                        int temp = intArray[i + 1];
                        intArray[i + 1] = intArray[i];
                        intArray[i] = temp;
                    }
                }
            }
            Console.WriteLine("After Sorting Array :");
            foreach (int item in intArray)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("The Loop iterates :" + count);
            Console.ReadKey();
        }
    }
}
Output:
Bubble Sort in C# with Example

As you can see the number of iterates is 16. You can improve the performance of the bubble sort by using a bool flag.

Performance Improvement in Bubble sort:
In the following example, we are using a flag variable.
using System;
namespace LogicalPrograms
{
    class Program
    {
        static void Main(string[] args)
        {
            int count = 0;
            int[] intArray = new int[5];
            Console.WriteLine("Enter the Array Elements : ");
            for (int i = 0; i < intArray.Length; i++)
            {
                intArray[i] = int.Parse(Console.ReadLine());
            }
            bool flag = true;
            for (int i = 1; (i <= (intArray.Length - 1)) && flag; i++)
            {
                flag = false;
                for (int j = 0; j < (intArray.Length - 1); j++)
                {
                    count = count + 1;
                    if (intArray[j + 1] > intArray[j])
                    {
                        int temp = intArray[j];
                        intArray[j] = intArray[j + 1];
                        intArray[j + 1] = temp;
                        flag = true;
                    }
                }
            }
            Console.WriteLine("After Sorting Array :");
            foreach (int item in intArray)
            {
                Console.Write(item + " ");
            }
            Console.WriteLine();
            Console.WriteLine("The Loop iterates :" + count);
            Console.ReadKey();
        }
    }
}
Output:
Performance Improvement in C# Bubble sort

Time Complexity of Bubble Sort:
In bubble sort, as we are iterating through the entire array for each element, the average and the worst-case complexity of bubble sort is O(n²).

Algorithm for Bubble Sort:

Procedure BubbleSort(DATA: list of sortable items)
N= DATA.Length
1. Set Flag: = True
2. Repeat Steps from 3 to 5 for I = 1 to N-1 while Flag == true
3. Set Flag:= False
4. Set J:=0. [Initialize pass pointer J]
5. Repeat while JDATA[J], then:
       Swap DATA[J] and DATA[J+1]
       Set Flag:= True
       [End of If structure]

       (b) Set J:=J+1
       [End of inner loop]
       [End of step 1 outer loop]

6. Exit
In the next article, I am going to discuss the Merge Sort Algorithm In C# with examples. Here, in this article, I try to explain the Bubble Sort in C# with example. I hope now you understood how bubble sort works in C# and I also hope you enjoy this article.

Summary:
I hope this post will be helpful to understand the concept of Bubble Sort in C#
Please share this post with your friends and colleagues.
For any queries please post a comment below.
Happy Coding 😉
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post

0 comments:

Post a Comment

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...
  • C# Programming Examples on Sorting
    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:  Sel...
  • Calling Web API Service in a Cross-Domain Using jQuery AJAX
    In this article, I am going to discuss Calling Web API Service in a Cross-Domain Using jQuery AJAX . Please read our previous article befor...
  • ViewBag in ASP.NET Core MVC
    In this article, I am going to discuss the use of ViewBag in ASP.NET Core MVC application with examples. Please read our previous article ...
  • Recursion And Back Tracking
    In this article, I am going to discuss Recursion And BackTracking in detail. Please read our previous article where we discussed Master Th...
  • 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...
  • Binary to Decimal Conversion in C# with Examples
    In this article, I am going to discuss the Binary to Decimal Conversion in C# with some examples. Please read our previous article where w...

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