每次将最大的元素放到数组的最后
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
//调用冒泡排序的int 数组
int[] testArray = { 1, 3, 9, 4, 5, 3, 2, 5, 4, 5, 8, 8, 8 };
BubbleSortHelper bsh = new BubbleSortHelper();
int[] result = bsh.BubbleSortIntArray(testArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < result.Count(); i++)
{
sb.Append(result[i] + ",");
}
sb.Remove(sb.Length - 1, 1);
Console.WriteLine(sb);
Console.ReadLine();
}
}
public class BubbleSortHelper
{
public int[] BubbleSortIntArray(int[] intArray)
{
int[] array = new int[intArray.Count()];
if (intArray.Count() == 0)
{
return array;
}
int length = intArray.Length;
int temp = 0;
for (int i = 0; i < length - 1; i++)//冒泡排序,两两比较,小的在前,大的在后
{
for (int j = 0; j < length - 1 - i; j++)
{
if (intArray[j] > intArray[j + 1])
{
temp = intArray[j];
intArray[j] = intArray[j + 1];
intArray[j + 1] = temp;
}
}
}
array = intArray;
return array;
}
}
}
相对于之前的冒泡排序法,这种方法耗时更短,每次将最大的元素放到最后就不再管它,之前需要循环的次数为N的平方,现在循环的次数为N!