您的位置:首页 > 编程语言 > Java开发

堆排序构建大根堆 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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: