使用冒泡算法,让数组中数完成从小到大排序。

冒泡排序(Bubble Sort),是一种计算机科学领域的较简单的排序算法

它重复地走访过要排序的元素列,一次比较两个相邻的元素,如果他们的顺序(如从大到小、首字母从A到Z)错误就把他们交换过来。走访元素的工作是重复地进行直到没有相邻元素需要交换,也就是说该元素已经排序完成。
这个算法的名字由来是因为越大的元素会经由交换慢慢“浮”到数列的顶端(升序或降序排列),就如同碳酸饮料中二氧化碳的气泡最终会上浮到顶端一样,故名“冒泡排序”。

C#语言

using Sys­tem;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

name­space ConsoleApplication1  数组排序
{
class Program
{
sta­t­ic void Main(string[] args)
{
int temp = 0;
int[] arr = { 23, 44, 66, 76, 98, 11, 3, 9, 7 };
//显示排序前的数组
Console.WriteLine(“排序前的数组:”);
fore­ach (int item in arr)
{
Console.Write(item + ” ”);
}
Console.WriteLine();
for (int i = 0; i < arr.Length — 1; i++)
{
//将大的数字移到数组的arr.Length-1‑i
for (int j = 0; j < arr.Length — 1 — i; j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
Console.WriteLine(“排序后的数组:”);
fore­ach (int item in arr)
{
Console.Write(item + ” ”);
}
Console.WriteLine();
Console.ReadKey();

}
}
}

为您推荐

发表评论

您的电子邮箱地址不会被公开。