日期:2014-05-17  浏览次数:20928 次

冒泡排序 C#

using System;

namespace SortingAlgorithms
{

??? class SortingAlgorithms
??? {
??????? private int[] arr;
??????? private int upper;
??????? private int numElement;

??????? //初始化数组?
??????? public SortingAlgorithms(int size)
??????? {
??????????? arr = new int[size];
??????????? upper = size - 1;
??????????? numElement = 0;
??????? }

??????? //给数组插入元素?
??????? public void Insert(int item)
??????? {
??????????? arr[numElement] = item;
??????????? numElement++;
??????? }

??????? //打印数组元素?
??????? public void DisplayElement()
??????? {
??????????? for (int i = 0; i <= upper; i++)
??????????? {
??????????????? Console.WriteLine(arr[i] + " ");
??????????? }
??????????? Console.ReadLine();
??????? }

??????? //冒泡排序?
??????? public void BubbleSort()
??????? {
??????????? int Temp;
??????????? //外循环是限制一次冒泡排序比较的元素个数?
??????????? for (int Outer = upper; Outer >= 1; Outer--)
??????????? {
??????????????? //一次冒泡排序比较0~ourter-1个元素的大小?
??????????????? for (int Inner = 0; Inner <= Outer - 1; Inner++)
??????????????? {
??????????????????? //排序过程?
??????????????????? if (arr[Inner] > arr[Inner + 1])
??????????????????? {
??????????????????????? Temp = arr[Inner];
??????????????????????? arr[Inner] = arr[Inner + 1];
??????????????????????? arr[Inner + 1] = Temp;
??????????????????? }
??????????????? }
??????????? }
??????????? //this.DisplayElement();?
??????? }

??????? //调用算法的过程
??????? static void Main(string[] args)
??????? {
??????????? SortingAlgorithms MyArray = new SortingAlgorithms(10);
??????????? Random rnd = new Random(100);
??????????? for (int i = 0; i < 10; i++)
??????????? {
??????????????? MyArray.Insert((int)(rnd.NextDouble() * 100));
??????????? }
??????????? Console.WriteLine("Before Sorting:");
??????????? MyArray.DisplayElement();
??????????? //进行排序?
??????????? MyArray.BubbleSort();
??????????? Console.WriteLine("After sorting");
??????????? //打印排序后的元素?
??????????? MyArray.DisplayElement();
??????? }
??? }
}