using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BubbleSort
{
internal class Program
{
public static void Main(string[] args)
{
int[] arr = { 9, 3, 8, 3, 5, 2 };
Console.WriteLine("冒泡排序前:");
PrintArray(arr);
BubbleSort(arr);
Console.WriteLine("冒泡排序后:");
PrintArray(arr);
Console.ReadKey();
}
public static void BubbleSort(int[] arr)
{
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - i - 1; j++)
{
if (arr[j] > arr[j + 1])
{
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
Console.Write("第" + (i + 1) + "轮排序后: ");
PrintArray(arr);
}
}
//定义打印数组的方法
public static void PrintArray(int[] arr)
{
//循环遍历数组的元素
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");//打印元素和空格
}
Console.WriteLine();
}
}
}
运行结果