/// <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;
}
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();
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有