Files
Csharp/C#基础/Lesson13_冒泡排序练习/Program.cs
T
2025-09-30 16:49:43 +08:00

60 lines
1.6 KiB
C#

using System;
namespace Lesson
{
class Program
{
static void Print(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
static void Main(string[] args)
{
int[] arr = new int[20];
Random r = new Random();
for (int i = 0; i < arr.Length; i++)
{
arr[i] = r.Next(0,101);
}
Print(arr);
int temp;
bool isSort;
for (int i = 0; i < arr.Length; i++)
{
isSort = false;
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] > arr[j + 1])
{
isSort = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (!isSort) { break; }
}
Print(arr);
for (int i = 0; i < arr.Length; i++)
{
isSort = false;
for (int j = 0; j < arr.Length - 1 - i; j++)
{
if (arr[j] < arr[j + 1])
{
isSort = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if (!isSort) { break; }
}
Print(arr);
}
}
}