每次將最大的元素放到數(shù)組的最后
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication2
{
? ? class Program
? ? {
? ? ? ? static void Main(string[] args)
? ? ? ? {
? ? ? ? ? ? //調(diào)用冒泡排序的int 數(shù)組
? ? ? ? ? ? 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;
? ? ? ? }
? ? }
}
相對于之前的冒泡排序法,這種方法耗時更短黎烈,每次將最大的元素放到最后就不再管它习柠,之前需要循環(huán)的次數(shù)為N的平方,現(xiàn)在循環(huán)的次數(shù)為N!