写一段程序,找出数组中第k大小的数,输出数所在的位置。
2016-05-17 15:18
417 查看
基本上是利用排序思想,稍微改造以适应这种需求。比如最简单的冒泡排序,冒泡到第k次时就找到了这个数(需要提前缓存原始索引位置);快速排序的思想,把数组分割成大于和小于某值的两部分后,判断每部分的元素个数,然后递归分割,等等。
下面这个代码是基于快排的思想:
下面这个代码是基于快排的思想:
using System; namespace test01 { class Program { static int sortCount = 0; static void Main(string[] args) { int [] array = {2,3,5,6,4,1,8}; Console.Write("数组未排序: "); foreach (int s in array) { Console.Write(" " + s); } Console.WriteLine(""); int k = 2; int i = FastFind(array, 0, 6, k); Console.WriteLine("第"+k+"个大的数是: "+i); Console.ReadKey(); } //在start到end位置寻找第k个大的数 static int FastFind(int[] array, int start, int end, int k) { int arraySize = array.Length; if (start < 0 || end >= arraySize || k > arraySize) return -1; //返回不合格的数字,如果数组里面有负数,需要修改 int low = start, high = end; int bs = array[low]; while (low < high) { while (array[high] >= bs && high > low) { high--; } if (high > low) { array[low] = array[high]; low++; } while (array[low] <= bs && low < high) { low++; } if (low < high) { array[high] = array[low]; high--; } } array[low] = bs; Console.Write("第" + (++sortCount) + "次排序后:"); foreach(int s in array) { Console.Write(" "+s); } Console.WriteLine(""); int rightCount = end - low; //右侧还有几个数 if (rightCount == k - 1) //此次排序右侧有(k-1)个数大于 bs,则bs正是第k个大的数 { return bs; } else if (rightCount < k - 1) //即第k个大的数存在于左侧 { return FastFind(array, start, low - 1, k - rightCount - 1); } else //右侧有很多数大于bs,即第k个大的数存在于右侧 { return FastFind(array, low + 1, end, k); } } } }输出:
相关文章推荐
- Java 虚拟机 gc算法总结
- 关于Apache2: Could not reliably determine the server’s fully qualified domain name, using 127.0.1.1 fo
- 网页下载判断是iOS和Android
- 在ASP.NET 2.0中操作数据之五十九:使用SQL缓存依赖项SqlCacheDependency
- ScheduledExecutorService遇到异常后续任务不继续执行的问题
- solr中文分词器IK-analyzer安装
- C/C++ TCP客户端、服务器简单示例
- win7下配置OpenCV的Qt开发环境
- Bootstrap静态cdn
- 【android学习】带清除功能的EditText重写
- [Magento SQL] 返回sku,price,specialPrice,上下架状态,库存
- 弹性分布式数据集RDD概述
- 致敬词
- C++中两个大整数相乘
- ASDM Installation and Troubleshooting
- .bss段和.data段的区别
- 在table中<tr>的display:block显示布局错乱
- 【leetcode】104. Maximum Depth of Binary Tree
- iOS: performSelectorOnMainThread waitUntilDone 参数详解
- defer、async属性以及JS异步加载并执行解决方案