内容简介:本题目借助快排思想,算法描述:代码:算法复杂度分析:
本题目借助快排思想,算法描述:
- a为待 排序 数组,n为数组长度
-
问题转换:把第k大数字转换成第l小数字,比如:
n=5,k=1,那么l=n-k+1=5,也就是第5小的数字,其下标l_i=5-1=4。 -
取
a[n-1]作为 pivot -
用快排的思路,把
< pivot的元素放到 pivot 左边,把>= pivot的元素放到 pivot 右边,得到pivot的下标:pivot_i -
如果
pivot_i < l_i,则说明被查找的数字可能在右边,对右边重复2-5步骤 -
如果
pivot_i > l_i,则说明被查找的数字可能在左边,对左边重复2-5步骤
代码:
public static int findKthBigNumber(int[] a, int kthBig) {
int n = a.length;
int lthSmall = n - kthBig;
return quickFind(a, 0, a.length - 1, lthSmall);
}
private static int quickFind(int[] a, int start, int end, int lthSmall) {
if (start > end) {
return -1;
}
int pivot = a[end];
int pivot_i = start;
for (int j = start; j <= end - 1; j++) {
if (a[j] < pivot) {
int tmp = a[j];
a[j] = a[pivot_i];
a[pivot_i] = tmp;
pivot_i++;
}
}
a[end] = a[pivot_i];
a[pivot_i] = pivot;
if (pivot_i == lthSmall) {
return a[pivot_i];
}
if (pivot_i < lthSmall) {
return quickFind(a, pivot_i + 1, end, lthSmall);
}
return quickFind(a, start, pivot_i - 1, lthSmall);
}
算法复杂度分析:
最好情况:
k > n
最坏情况:
(n-1)+(n-2)+(n-3)+...+1=n(n-1)/2
平均情况:
- 不知怎么分析
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
C和C++代码精粹
阿林森 / 董慧颖 / 人民邮电出版社 / 2003-4-1 / 59.00
《C和C++代码精粹》基于作者备受好评的C/C++ User Journal杂志上的每月专栏,通过大量完全符合ISO标准C++的程序集合,说明了C++真正强大的威力,是C和C++职业程序员的实践指南。可以帮助有一定经验的C和C++程序员深入学习这两种密切相关的语言,对书中代码的参悟和应用,可以帮助他们从根本上提高使用程序的效率。一起来看看 《C和C++代码精粹》 这本书的介绍吧!