当前位置: 移动技术网 > IT编程>开发语言>c# > C#不重复输出一个数组中所有元素的方法

C#不重复输出一个数组中所有元素的方法

2019年07月18日  | 移动技术网IT编程  | 我要评论

本文实例讲述了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#程序设计有所帮助。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网