堆排序构建大根堆 java
2017-09-17 23:48
183 查看
private static int[] test(int[] a)
{
int total = a.length;
for(int i = 2; i >= 0; i--)
{
int k = (int) Math.pow(2, i + 1) -1;
int count = (int) Math.pow(2, i) - 1;
for(int num = 0, j = k - 1 - count; num <= count; j++)
{
int left = j * 2 + 1;
int right = j * 2 + 2;
int max = 0;
if(left >= total)
{
left = -1;
break;
}
if(right >= total)
{
right = - 1;
}
if(left != -1)
{
max = a[left];
if(right < total && max < a[right])
{
max = a[right];
if(max > a[j])
{
max = a[right];
a[right] = a[j];
a[j] = max;
}
}
if(right < total && max > a[right])
{
if(max > a[j])
{
max = a[left];
a[left] = a[j];
a[j] = max;
}
}
if(right == -1)
{
if(a[j] < max)
{
max = a[left];
a[left] = a[j];
a[j] = max;
}
}
}
}
}
return a;
}
{
int total = a.length;
for(int i = 2; i >= 0; i--)
{
int k = (int) Math.pow(2, i + 1) -1;
int count = (int) Math.pow(2, i) - 1;
for(int num = 0, j = k - 1 - count; num <= count; j++)
{
int left = j * 2 + 1;
int right = j * 2 + 2;
int max = 0;
if(left >= total)
{
left = -1;
break;
}
if(right >= total)
{
right = - 1;
}
if(left != -1)
{
max = a[left];
if(right < total && max < a[right])
{
max = a[right];
if(max > a[j])
{
max = a[right];
a[right] = a[j];
a[j] = max;
}
}
if(right < total && max > a[right])
{
if(max > a[j])
{
max = a[left];
a[left] = a[j];
a[j] = max;
}
}
if(right == -1)
{
if(a[j] < max)
{
max = a[left];
a[left] = a[j];
a[j] = max;
}
}
}
}
}
return a;
}
相关文章推荐
- Java构建Heap,进行Heap 排序(堆排序)
- Java实现堆排序(大根堆)
- Java实现堆排序(大根堆)
- Java实现堆排序(大根堆)
- Java代码构建一个线程池
- 堆排序之java
- 使用IntelliJ IDEA和Maven构建Java web项目并打包部署
- Java使用MyEclipse构建webService简单案例
- 转:Java SoftReference 使用构建对象缓存
- Maven构建java项目详细步骤
- java面试算法之堆排序
- Java并发基础构建模块简介
- java构建模式
- Java编码 蛇形矩阵的构建与遍历输出
- Spring3.2.0+Hibernate4.1.9+Activiti5.12.1 MAVEN构建JAVA WEB应用之POM.xml
- 利用apache+svn+jenkins+maven 实现java环境的自动化构建和部署(二)(网内首发超详细版)
- 构建一个 Java 桌面数据库应用程序
- Java学习之类的构建方法(函数)
- 堆排序(JAVA)实现和杨氏矩阵查找
- Gradle用户指南(3)-构建Java项目