C#控制台冒泡程序
1首先在VS中新建一个项目
在生成的代码中添加少许代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleHelloWorld
{
class Program
{
static void Main(string[] args)
{
//快捷键运行CTRL+F5
//HelloWorld
Console.WriteLine("Hello World");
//声明一个整型数组
int[] nums = new int[] { 9, 123, 44, 1, 2, 55, 33, 22, 54, 66, 23 };
//调用冒泡排序
BubbleSort(nums);
//打印排序后的结果
PrintArr(nums);
}
//冒泡排序
static void BubbleSort(int[] nums)
{
for (int i = 0; i < nums.Length; i++)
{
for (int j = 0; j < nums.Length-i-1; j++)
{
//Console.WriteLine("当前:" + i + "," + j+"比较:"+ nums[j] +","+ nums[j + 1]);
if (nums[j] > nums[j+1])
{
int temp = nums[j];
nums[j] = nums[j+ 1];
nums[ j + 1] = temp;
}
}
}
Console.WriteLine(nums);
}
//打印数组
static void PrintArr(int[] arr)
{
//遍历数组
foreach(int i in arr)
{
//打印该元素并以逗号分隔
Console.Write(i + ",");
}
//换行
Console.WriteLine("");
}
}
}