public static void heapSort(int[]nums)
{
int len=nums.length;
for(int i=len/2;i>=0;i--)
{
sort(nums,i,len);
}
for(int i=len-1;i>0;i--)
{
swap(nums,0,i);
sort(nums,0,i);
}
}
public static void sort(int[] nums,int index,int len)
{
int left;
int right;
int leftValue,rightValue;
while (index<len)
{
left=index*2+1;
right=index*2+2;
leftValue=left>=len?Integer.MAX_VALUE:nums[left];
rightValue=right>=len?Integer.MAX_VALUE:nums[right];
if(leftValue<nums[index]&&leftValue<=rightValue)
{
swap(nums,left,index);
index=left;
}else
if(rightValue<nums[index]&&rightValue<leftValue)
{
swap(nums,right,index);
index=right;
}
else
{
break;
}
}
}
public static void swap(int[]nums,int a,int b)
{
int tem=nums[a];
nums[a]=nums[b];
nums[b]=tem;
}
堆排序
最新推荐文章于 2024-11-05 21:58:11 发布