有一個整數陣列,請你根據快速排序的思路,找出陣列中第K大的數。 給定一個整數陣列a,同時給定它的大小n和要找的K(K在1到n之間),請返回第K大的數,保證答案存在。
阿新 • • 發佈:2019-01-06
一, 原快速排序的實現
http://blog.csdn.net/taotaoah/article/details/50987837
二,根據題意修改如下: 測試樣例:using System; namespace taotao { class program { static void Main(string[] args) { int[] array = new int[] { 1, 3, 5, 2, 2 }; array = quick_sort(array, 0, array.Length - 1); foreach (var item in array) { Console.WriteLine(item); } } static int[] quick_sort(int[] array, int start, int end) { if (start < end) { int i = start; int j = end; int x = array[i]; while (i < j) { while (i < j && array[j] >= x) j--; if (i < j) array[i++] = array[j]; while (i < j && array[i] < x) i++; if (i < j) array[j--] = array[i]; } array[i] = x; quick_sort(array, start, i - 1); quick_sort(array, i + 1, end); } return array; } } }
[1,3,5,2,2],5,3
返回:2
using System; namespace taotao { class program { static void Main(string[] args) { int[] array = new int[] { 1, 3, 5, 2, 2 }; int K = 3; array = quick_sort(array, 0, array.Length - 1); foreach (var item in array) { Console.WriteLine(item); } Console.Write(Fun(array, array.Length, K)); } static int[] quick_sort(int[] array, int start, int end) { if (start < end) { int i = start; int j = end; int x = array[i]; while (i < j) { while (i < j && array[j] >= x) j--; if (i < j) array[i++] = array[j]; while (i < j && array[i] < x) i++; if (i < j) array[j--] = array[i]; } array[i] = x; quick_sort(array, start, i - 1); quick_sort(array, i + 1, end); } return array; } static int Fun(int[] array, int len, int K) { return array[K - 1]; } } }