
- C# Basic Tutorial
- C# - Home
- C# - Overview
- C# - Environment
- C# - Program Structure
- C# - Basic Syntax
- C# - Data Types
- C# - Type Conversion
- C# - Variables
- C# - Constants
- C# - Operators
- C# - Decision Making
- C# - Loops
- C# - Encapsulation
- C# - Methods
- C# - Nullables
- C# - Arrays
- C# - Strings
- C# - Structure
- C# - Enums
- C# - Classes
- C# - Inheritance
- C# - Polymorphism
- C# - Operator Overloading
- C# - Interfaces
- C# - Namespaces
- C# - Preprocessor Directives
- C# - Regular Expressions
- C# - Exception Handling
- C# - File I/O
- C# Advanced Tutorial
- C# - Attributes
- C# - Reflection
- C# - Properties
- C# - Indexers
- C# - Delegates
- C# - Events
- C# - Collections
- C# - Generics
- C# - Anonymous Methods
- C# - Unsafe Codes
- C# - Multithreading
- C# Useful Resources
- C# - Questions and Answers
- C# - Quick Guide
- C# - Useful Resources
- C# - Discussion
Bubble Sort program in C#
Bubble sort is a simple sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.
Let’s say our int has 5 elements −
int[] arr = { 78, 55, 45, 98, 13 };
Now, let us perform Bubble Sort.
Start with the first two elements 78 and 55. 55 is smaller than 78, so swap both of them. Now the list is −
55, 78,45,98, 13
Now 45 is less than 78, so swap it.
55, 45, 78, 98, 3
Now 98 is greater than 78, so keep as it is.
3 is less than 98, so swap it. Now the list looks like −
55, 45, 78, 3, 98
This was the first iteration. After performing all the iterations, e will get our sorted array using Bubble Sort −
3, 45, 55, 78, 93
Example
Let us see an example with 10 elements in an array and sort it.
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
Sorted: 13 45 55 78 98
- Related Articles
- C++ Program to Implement Bubble Sort
- C++ Program for Recursive Bubble Sort?
- C Program for Recursive Bubble Sort
- C++ Program for the Recursive Bubble Sort?
- 8085 program for bubble sort
- Python Program for Bubble Sort
- Java program to implement bubble sort
- Java Program for Recursive Bubble Sort
- Bubble Sort
- C program to sort a given list of numbers in ascending order using Bubble sort
- Swift Program to Implement Bubble Sort Algorithm
- Bubble sort in Java.
- Swift Program to sort an array in ascending order using bubble sort
- Swift Program to sort an array in descending order using bubble sort
- 8085 Program to perform bubble sort in ascending order

Advertisements