using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
///对数组进行排序
namespace 冒泡排序
{
class Program
{
static void Main(string[] args)
{
Console.Write("请输入随机产生数组的长度:");
int length =Convert.ToInt32(Console.ReadLine());
//随机产生数组
Random ra = new Random();
int[] a = new int[length];
for (int i = 0; i < length; i++)
{
a[i] = ra.Next(0, 101);
}
Console.WriteLine("数组取值范围0到100!\n未排序:");
PrintResult(a, length);
Console.WriteLine();
SortData(a, length);
Console.WriteLine("已排序:");
PrintResult(a, length);
}
/// <summary>
/// 对一定长度(length)的数组(a[])排降序
/// </summary>
/// <param name="a"></param>
/// <param name="length"></param>
public static void SortData(int[] a, int length)
{
for (int x = 0; x < length; x++)
{
for (int y = x + 1; y < length; y++)
{
if (a[x] < a[y])
{
int temp = a[y];
a[y] = a[x];
a[x] = temp;
}
}
}
}
/// <summary>
/// 按一定格式输出数组
/// </summary>
/// <param name="a"></param>
/// <param name="length"></param>
public static void PrintResult(int[] a, int length)
{
for (int j = 0; j < length; j++)
{
if (a[j] < 10)
{
Console.Write(" " + a[j] + ", ");
}
else
{
if (a[j] == 100)
{
Console.Write(a[j] + ", ");
}
else
{
Console.Write(" " + a[j] + ", ");
}
}
if ((j+1) % 10 == 0)
{
Console.WriteLine();
}
}
Console.ReadKey();
}
}
}
C# 随机产生一定长度数组并对其排序
最新推荐文章于 2024-02-08 18:15:48 发布