冒泡算法,都忘了怎么写了,只写出来一个最差最差的两层循环 。。。今天在网上查了查资料,写成了程序
using
System;
using
System.Collections.Generic;
using
System.Text;
namespace
Algorithm_Demonstrate
{
class Program
{
static void Main(string[] args)
{
int[] a = new int[] {9,8,7,6,5,4,3,2,1,0 };
for (int i = 0; i < a.Length; i++)
{
Console.WriteLine(a[i]);
}
Bubblesort objbullsort = new Bubblesort();
int sorttime=objbullsort.BubblesortMethod(a);
for( int i=0;i<a.Length;i++)
{
Console.WriteLine(a[i]);
}
Console.WriteLine("sort time is :" + sorttime);
Console.ReadLine();
}
}
class Bubblesort
{
public int BubblesortMethod(int[] ary)
{//ary is the arry to storage the DATA needed to sort
bool ischange;
int time = 0;
for (int i = 0; i < ary.Length; i++)
{
ischange = false;
for (int j = ary.Length - 1; j > i; j--)
{
if (ary[j] <= ary[j - 1])
Swap(ref ary[j], ref ary[j - 1]);
time++;
ischange = true;
}
if (!ischange)
return time;
}
return time;
}
void Swap(ref int a, ref int b)
{
a = a ^ b;
b = b ^ a;
a = a ^ b;
}
}
}