返回一个数组升序排列后的位置信息--C#程序举例
返回一个数组升序排列后的位置信息--C#程序举例
返回某一个数组升序排序后的位置 比如:{8,10,9,11}排序后应该是{8,9,10,11},但是需要返回{1,3,2,4}
这根本不需要排序,只需要找出比 对比的元素小的元素个数即可(有了这个思路)可以写程序了
程序方法如下
1 ///2 /// 返回一个数组升序后的位置信息 3 /// 4 /// 5 /// 6 private static int[] getAscendingIndex(int[] array) 7 { 8 int[] indexArray = new int[array.Length]; 9 for (int i = 0; i < array.Length; i++) 10 { 11 int index = 0; 12 for (int j = 0; j < array.Length; j++) 13 { 14 if (array[j]<= array[i]) 15 { 16 index++; 17 } 18 } 19 indexArray[i] = index; 20 } 21 return indexArray; 22 }
测试程序如下:
1 static void Main(string[] args) 2 { 3 int[] ArrayTest = new int[4]{8,10,9,11}; 4 int[] resultArray = getAscendingIndex(ArrayTest); 5 for (int i = 0; i < resultArray.Length; i++) 6 { 7 Console.WriteLine(resultArray[i]); 8 } 9 10 Console.Read(); 11 }
输出结果:
源程序有需要的可以下载
源代码工程文件下载
各位大侠,如果有更好的方法算法复杂度更低,麻烦给出,感激!欢迎留言