- List item
冒泡排序
//冒泡排序 就是将一个数组中的元素按照从大到小或者从小到大的顺序进行排列。
冒泡排序用到了定义数组,for循环的使用,for循环的嵌套等等
定义数组的语法:
语法:
1、数组类型[] 数组名=new 数组类型[数组长度];
2、数组类型[] 数组名={n1,n2,n3,其他数组的元素}
for循环的语法
语法:
for(表达式1;表达式2;表达式3)
{
循环体;
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp42
{
class Program
{
static void Main(string[] args)
{
//冒泡排序 就是将一个数组中的元素按照从大到小或者从小到大的顺序进行排列。
int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int i = 0; i < nums.Length-1; i++)
{
for (int j = 0; j < nums.Length-1-i; j++)
{
if(nums[j]<nums[j+1])
{
int a = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = a;
}
}
}
for (int i = 0; i < nums.Length; i++)
{
Console.WriteLine(nums[i]);
}
Console.ReadKey();
}
}
}