BubbleSort
Written by: maffelu , 2009-09-15 10:32:51
| Array | Element to check | Swap? |
|---|---|---|
| 3, 2, 5, 1, 4 | 3 | Yes |
| 2, 3, 5, 1, 4 | 3 | No |
| 2, 3, 5, 1, 4 | 5 | Yes |
| 2, 3, 1, 5, 4 | 5 | Yes |
| 2, 3, 1, 4, 5 | 5 | Yes |
| Array | Element to check | Swap? |
|---|---|---|
| 2, 3, 1, 4, 5 | 2 | No |
| 2, 3, 1, 4, 5 | 3 | Yes |
| 2, 1, 3, 4, 5 | 3 | Yes |
| 2, 1, 3, 4, 5 | 4 | No |
| 2, 1, 3, 4, 5 | 5 | No |
| Array | Element to check | Swap? |
|---|---|---|
| 2, 1, 3, 4, 5 | 2 | Yes |
| 1, 2, 3, 4, 5 | 2 | No |
| 1, 2, 3, 4, 5 | 3 | No |
| 1, 2, 3, 4, 5 | 4 | No |
| 1, 2, 3, 4, 5 | 5 | No |
using System;
namespace MorkaBubbleSort {
class Program {
static void Main(string[] args) {
//Our example array
int[] arr = new int[] { 3, 2, 5, 1, 4 };
Console.WriteLine("Unsorted:");
displayElements(arr);
sort(arr);
Console.WriteLine("Sorted:");
displayElements(arr);
Console.Read();
}
static void displayElements(int[] arr) {
foreach (int i in arr) {
Console.Write("{0, -3}", i);
}
Console.Write("\n");
}
static void sort(int[] arr) {
int temp;
//Start from the end and move backwards
for (int outer = arr.Length - 1; outer >= 1; outer--) {
//Start from the beginning, but only go as far as to the current outer element
for (int inner = 0; inner <= outer - 1; inner++) {
//Only swap if the current number to check is larger
//than its element to the right
if (arr[inner] > arr[inner + 1]) {
//We'll save the number we're checking
temp = arr[inner];
//We'll add the number to the right to the current number
arr[inner] = arr[inner + 1];
//We place the number we are checking to the right,
//thus ending the swap
arr[inner + 1] = temp;
}
}
}
}
}
}
There are no comments on this article.
If you have any question or just want to leave a message, just fill out the form below!
Your e-mail will not be visible in your post, it is for validation reasons only
Maffelu
Creator and admin of MorkaLork.com.
Started programming in HTML back when frames and tables was the way to design a page, moved on to Pascal/Delphi, PHP, javascript/jQuery, VB.NET/C#, Java and C++.
Currently studies .NET (in general) focusing on ASP.NET.