- 本例中主要介绍C#冒泡排序方法,输出排序后的数组,一共执行了几轮以及每轮比较的次数。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace maopaosort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 8, 1, 5, 3, 9, 2, 6 };
int[] arr2=new int[6];
int temp;
Console.WriteLine("原数组为:");
foreach (int k in arr)
{
Console.Write(k + " ");
}
Console.WriteLine();
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
arr2[i]++;
}
}
Console.WriteLine("转换后的数组为:");
foreach (int k in arr)
{
Console.Write(k + " ");
}
Console.WriteLine();
Console.WriteLine("一共比较了:{0}轮",arr.Length-1);
Console.WriteLine("数组每轮的比较次数分别为:");
for(int k=0;k<arr2.Length;k++)
{
Console.Write("{0} ",arr2[k]);
}
Console.WriteLine();
Console.ReadKey();
}
}
}