本文實例講述了C#不重復輸出一個數組中所有元素的方法。分享給大家供大家參考。具體如下:
1.算法描述
0)輸入合法性校驗
1)建立臨時數組:與原數組元素一樣。該步驟的目的是防止傳入的原數組被破壞
2)對臨時數組進行排序
3)統計臨時數組共有多少個不同的數字。該步驟的目的是為了確定結果集數組的長度
4)建立結果集數組,只存放不同的數字
5)返回結果集
2.函數代碼
/// <summary>/// 建立包含原數組內所有元素且元素間互不重復的新數組/// </summary>/// <param name="array">原數組</param>/// <param name="isAsc">true:升序排列/false:降序排列</param>/// <returns>新數組</returns>private static int[] DifferentElements(int[] array, bool isAsc = true){ //0.輸入合法性校驗 if (array == null || array.Length == 0) { return new int[] { }; } //1.臨時數組:與原數組元素一樣 int[] tempArray = new int[array.Length]; for (int i = 0; i < tempArray.Length; i++) { tempArray[i] = array[i]; } //2.對臨時數組進行排序 int temp; for (int i = 0; i < tempArray.Length; i++) { for (int j = i; j < tempArray.Length; j++) { if (isAsc) { if (tempArray[i] > tempArray[j]) { temp = tempArray[i]; tempArray[i] = tempArray[j]; tempArray[j] = temp; } } else { if (tempArray[i] < tempArray[j]) { temp = tempArray[i]; tempArray[i] = tempArray[j]; tempArray[j] = temp; } } } } //3.統計臨時數組共有多少個不同的數字 int counter = 1; for (int i = 1; i < tempArray.Length; i++) { if (tempArray[i] != tempArray[i - 1]) { counter++; } } //4.建立結果集數組 int[] result = new int[counter]; int count = 0; result[count] = tempArray[0]; for (int i = 1; i < tempArray.Length; i++) { if (tempArray[i] != tempArray[i - 1]) { count++; result[count] = tempArray[i]; } } //5.返回結果集 return result;}
3.Main函數調用
static void Main(string[] args){ int[] array = new int[] { 1, 9, 1, 9, 7, 2, 2, 5, 3, 4, 5, 6, 3, 3, 6, 2, 6, 7, 8, 0 }; //數組:包含原數組內全部元素且不重復(升序排列) int[] result1 = DifferentElements(array); foreach (int i in result1) { Console.Write(i.ToString() + "/t"); } //數組:包含原數組內全部元素且不重復(降序排列) int[] result2 = DifferentElements(array,false); foreach (int i in result2) { Console.Write(i.ToString() + "/t"); } Console.ReadLine();}
4.程序輸出示例
希望本文所述對大家的C#程序設計有所幫助。
新聞熱點
疑難解答