C#冒泡排序 红太狼 2021-06-24 16:10 433阅读 0赞 冒泡排序,helper帮助类,里面写一了一个给int数组排序的的非静态方法,然后将排序好的数组返回。 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SortHelper { 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; } } } 在main方法中调用该排序方法…… using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SortHelper { 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(); } } } 执行结果: ![2789632-d8ab39ce03d2420b.png][] 冒泡排序 [2789632-d8ab39ce03d2420b.png]: /images/20210615/7398d5b59c534dd8a83754e9bffa442b.png
还没有评论,来说两句吧...