Java 使用HeapSort对数组排序

Java 使用HeapSort对数组排序,java,arrays,sorting,heapsort,Java,Arrays,Sorting,Heapsort,我们必须用随机数对数组进行排序。为此,我们需要使用这部分代码(HeapSort) import java.util.ArrayList; 公共类HeapSort{ 公共阵列列表h; 公共整数大小; 公共int n; 公共堆填区(int s){ 尺寸=s; n=1; h=新阵列列表(大小); for(int i=0;i交换) 如果(LT(ils、irs)){ 交换(ip,ils);//向左向下交换 ip=ils; ils=ip*2; irs=ils+1; } 否则{ 交换(ip,irs);//右下

我们必须用随机数对数组进行排序。为此,我们需要使用这部分代码(HeapSort)

import java.util.ArrayList;
公共类HeapSort{
公共阵列列表h;
公共整数大小;
公共int n;
公共堆填区(int s){
尺寸=s;
n=1;
h=新阵列列表(大小);
for(int i=0;i交换)
如果(LT(ils、irs)){
交换(ip,ils);//向左向下交换
ip=ils;
ils=ip*2;
irs=ils+1;
}
否则{
交换(ip,irs);//右下交换
ip=irs;
ils=ip*2;
irs=ils+1;
}
}
}
其他的
//只剩下儿子
如果(存在(ils)&!存在(irs)){
如果(LT(ils,ip)){//左子小于父子
交换(ip、ils);
ip=ils;
ils=ip*2;
irs=ils+1;
}
}
//否则就没有孩子了,交换就结束了
}
}
公共布尔条件交换(int p,int l,int r){
//(有2个子项和(父项>左侧或父项>右侧))或
//(有1个子项和父项>左侧)
返回((存在(l)和存在(r))和(LT(l,p)| | LT(r,p)))||
(存在(l)&!存在(r)&<(l,p));
}
公共布尔值存在(int p){
如果(p>=大小)
返回false;
返回h.get(p)!=null;
}
公共无效掉期(整数a、整数b){
ec=h.get(a);
h、 集合(a,h.get(b));
h、 组(b,c);
}

公共布尔LT(inta,intb){//h[a]所有内容都在
HeapSort
类中,等待您使用它:

    int[] taula = {4, 2, 8, 1, 2, 3};
    System.out.println(Arrays.toString(taula));

    // 'heapSort' variable will store ordered list
    HeapSort<Integer> heapSort = new HeapSort<>(taula.length+1);

    for (Integer i : taula)
        heapSort.Insert(i);

    System.out.println(heapSort);
int[]taula={4,2,8,1,2,3};
System.out.println(array.toString(taula));
//“heapSort”变量将存储有序列表
HeapSort HeapSort=新HeapSort(taula.length+1);
for(整数i:taula)
heapSort.插入(i);
System.out.println(heapSort);

旁注:您应该遵守Java代码惯例,例如以小写字符开头的方法名称,以避免方法和类或其构造函数之间的混淆。此外,将数组馈送到
HeapSort
实例或读取排序数组/列表(或就地执行)有什么问题你试过使用那门课吗?
public class P3 {


public static void main(String[] args) {

   Scanner reader = new Scanner(System.in);  
   System.out.println("Quina llargada tindrà la taula? ");
   int n = reader.nextInt(); //n=llargada taula
   int[] taula = new int[n];


   int fi = 100*n;
   Random rand = new Random();
   //int al = rand.nextInt(fi) + 0;

   for (int i = 0; i < taula.length; i++) 
       taula[i] = rand.nextInt(fi);

System.out.println(Arrays.toString(taula)); }}
    int[] taula = {4, 2, 8, 1, 2, 3};
    System.out.println(Arrays.toString(taula));

    // 'heapSort' variable will store ordered list
    HeapSort<Integer> heapSort = new HeapSort<>(taula.length+1);

    for (Integer i : taula)
        heapSort.Insert(i);

    System.out.println(heapSort);