Featured

# Bubble Sort Program Using C#

I will explain in this article how to write a program for doing a Bubble Sort using C#. This type of question might be asked by an interviewer in a .Net position related interview.
My intent for this article is to explain how to answer a question that is often asked in an interview, which is: Write a program that does a Bubble Sort using C#. A candidate new to the interview can become totally confused because the first problem is the candidate does not know what a Bubble Sort is.
So considering the preceding requirement and numerous emails sent to me from beginners I have decided to write this article with the basics and specially focusing on the beginner, student and whoever might face this type of question in an interview.
What is a Sorting?
Sorting means arranging the items (numbers etc.) in a specified manner, in other words ascending or descending etc.
Example
10,1,8,2 unordered
1,2,8,10 ordered
I hope you now understand about sorting.
What does Bubble Sort Mean?
To change the postion of numbers or other items from right to left or left to right or any position as you wish, in other words changing an unordered sequence into an ordered sequence is called a Bubble Sort.
Example
Suppose I have the given input as:
4,5,3,2,1
Then the given numbers after the Bubble Sort are :
1,2,3,4,5
Now that we completely understand what is meant by Bubble Sorting, next I will explain how to do it step-by-step, as in the following:
1.   Open Visual Studio from Start - All programs - Microsoft Visual Studio.
2.  Then go to to "File" - "New" - "Project..." then select Visual C# - Windows - Console  application.
3.    After that specify the name such as Bubble Sort or whatever name you wish and the location of the project and click on the "OK" button. The new project is created.
And use the following code in the program.cs class file:

```using System;
namespace BubbleSortInCSharp
{
class bubblesort
{
static void Main(string[] args)
{
int[] a = { 3, 2, 5, 4, 1 }; // passing numbers through array
int t;
for (int p = 0; p <= a.Length - 2; p++)
{
for (int i = 0; i <= a.Length - 2; i++)
{
if (a[i] > a[i + 1])
{
t = a[i + 1];
a[i + 1] = a[i];
a[i] = t;
}
}
}
Console.WriteLine("This Application Created by vithal wadje for C# corner");
Console.WriteLine("The Sorted array");
foreach (int aa in a)                         //writting array
Console.Write(aa + " ");
}
}
}
```
The output of the above program will be:

From the above output it's clear that Bubble Sort means arranging the items with systematic ordered or as you wish to represent them.
Summary