冒泡排序,即相邻的两个数不断比较大小,直至最大值到达最右端,(从小到大)
举例如下:
15,65,85,63,66,312,62,74,10
第一次排序
第二次排序
依次比较。
算法设计:
- 遍历整个数组,确保每一个元素都能够经过;
- 依次比较相邻的两个数字大小,交换位置;
- 重复步骤1和步骤2
- 最多排序次数为数组长度,完成排序;
static public void bubblesort(int[] arr)
{
int a;
for (int i = arr.Length-1; i >0; i--)//遍历数组
{
for (int j =1 ; j < arr.Length ; j++)//依次比较相邻两个数
{
if (arr[j]<= arr[j-1])//比较大小,交换位置
{
a = arr[j-1];
arr[j-1 ] = arr[j];
arr[j] = a;
}
}
}
}
完整代码
using System;
namespace BubbleSort
{
class Program
{
static void Main(string[] args)
{
int[] arr = new int[] { 15, 65, 85, 63, 66, 312, 62, 74, 10 };
bubblesort(arr);
display(arr);
Console.ReadKey();
}
static public void bubblesort(int[] arr)
{
int a;
for (int i = arr.Length-1; i >0; i--)
{
for (int j =1 ; j < arr.Length ; j++)
{
if (arr[j]<= arr[j-1])
{
a = arr[j-1];
arr[j-1 ] = arr[j];
arr[j] = a;
}
}
}
}
static public void display(int[] arr)
{
for (int i = 0; i < arr.Length; i++)
{
Console.Write(arr[i] + " ");
}
Console.WriteLine();
}
}
}