最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法

 更新時(shí)間:2015年08月14日 09:50:15   作者:北風(fēng)其涼  
這篇文章主要介紹了C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法,涉及C#針對(duì)數(shù)組的遍歷、校驗(yàn)及排序等操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了C#不重復(fù)輸出一個(gè)數(shù)組中所有元素的方法。分享給大家供大家參考。具體如下:

1.算法描述

0)輸入合法性校驗(yàn)
1)建立臨時(shí)數(shù)組:與原數(shù)組元素一樣。該步驟的目的是防止傳入的原數(shù)組被破壞
2)對(duì)臨時(shí)數(shù)組進(jìn)行排序
3)統(tǒng)計(jì)臨時(shí)數(shù)組共有多少個(gè)不同的數(shù)字。該步驟的目的是為了確定結(jié)果集數(shù)組的長(zhǎng)度
4)建立結(jié)果集數(shù)組,只存放不同的數(shù)字
5)返回結(jié)果集

2.函數(shù)代碼

/// <summary>
/// 建立包含原數(shù)組內(nèi)所有元素且元素間互不重復(fù)的新數(shù)組
/// </summary>
/// <param name="array">原數(shù)組</param>
/// <param name="isAsc">true:升序排列/false:降序排列</param>
/// <returns>新數(shù)組</returns>
private static int[] DifferentElements(int[] array, bool isAsc = true)
{
 //0.輸入合法性校驗(yàn)
 if (array == null || array.Length == 0)
 {
  return new int[] { };
 }
 //1.臨時(shí)數(shù)組:與原數(shù)組元素一樣
 int[] tempArray = new int[array.Length];
 for (int i = 0; i < tempArray.Length; i++)
 {
  tempArray[i] = array[i];
 }
 //2.對(duì)臨時(shí)數(shù)組進(jìn)行排序
 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.統(tǒng)計(jì)臨時(shí)數(shù)組共有多少個(gè)不同的數(shù)字
 int counter = 1;
 for (int i = 1; i < tempArray.Length; i++)
 {
  if (tempArray[i] != tempArray[i - 1])
  {
   counter++;
  }
 }
 //4.建立結(jié)果集數(shù)組
 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.返回結(jié)果集
 return result;
}

3.Main函數(shù)調(diào)用

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
 };
 //數(shù)組:包含原數(shù)組內(nèi)全部元素且不重復(fù)(升序排列)
 int[] result1 = DifferentElements(array);
 foreach (int i in result1)
 {
  Console.Write(i.ToString() + "\t");
 }
 //數(shù)組:包含原數(shù)組內(nèi)全部元素且不重復(fù)(降序排列)
 int[] result2 = DifferentElements(array,false);
 foreach (int i in result2)
 {
  Console.Write(i.ToString() + "\t");
 }
 Console.ReadLine();
}

4.程序輸出示例

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論

威海市| 沁阳市| 峨山| 横山县| 庆元县| 沙坪坝区| 香河县| 扎鲁特旗| 武川县| 洱源县| 尖扎县| 白朗县| 海阳市| 扬州市| 囊谦县| 获嘉县| 和政县| 永胜县| 中牟县| 三穗县| 樟树市| 石泉县| 大连市| 华容县| 米林县| 绥芬河市| 习水县| 西乌珠穆沁旗| 德化县| 新乡市| 察雅县| 姜堰市| 淄博市| 城固县| 彩票| 奉新县| 湘阴县| 双牌县| 理塘县| 台东市| 吐鲁番市|