作业帮 > 综合 > 作业

c# 随机生成10个(0-100)的整数,并用冒泡法排序.

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/25 18:16:33
c# 随机生成10个(0-100)的整数,并用冒泡法排序.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Random rdm = new Random();
int[] arr = new int[10];
Console.WriteLine("排序前:");
for (int i = 0; i < 10; i++)
{
arr[i] = rdm.Next(0,100);
Console.Write(arr[i] + " ,");
}
Console.WriteLine("");
Console.WriteLine("排序后:");
Sort(arr);
}
public static void Sort(int[] arr)
{
for (int j = 1; j < arr.Length; j++)
{//外循环每次把参与排序的最大数排在最后
for (int i = 0; i < arr.Length - j; i++)
{ //内层循环负责对比相邻的两个数,并把最大的排在后面
if (arr[i] > arr[i + 1])
{ //如果前 一个数大于后一个数,则交换两个数
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
}
//用 一个循环访问数组里的元素并打印
for (int j = 0; j < arr.Length; j++)
{
Console.Write(arr[j] + " ,");
}
}
}
}