JAVA版的快排,堆排,筛法

    技术2022-05-13  2

     

    今天在实验课上写的 = =。。。

     

    java真麻烦,每个函数。。呃 。。。方法前面都得写个static。。。

     

    这个堆排是所有数都输好了堆排,不是拿出来一个,插入一个的那种。。

     

    觉得我这个不符合面向对象的思想捏。。。

     

     

    党说可以那么弄。。挺好的,下次试试。

     

    堆排

     

    import java.io.*; import java.util.*; public class HeapSort{ public static void heapMin(int a[],int i,int heapsize) { int tmp,larg; int lchild = i<<1,rchild = lchild+1; if( lchild <= heapsize && a[lchild] > a[i] ) larg = lchild; else larg = i; if( rchild <= heapsize && a[rchild] > a[larg] ) larg = rchild; if( larg != i ) { tmp = a[i]; a[i] = a[larg]; a[larg] = tmp; heapMin(a,larg,heapsize); } } public static void Heapsort(int a[],int n) { int heapsize = n; for(int i=n>>1; i>=1; i--) heapMin(a,i,n); for(int i=n; i>=2; i--) { int tmp; tmp = a[i]; a[i] = a[1]; a[1] = tmp; heapsize--; heapMin(a,1,heapsize); } } public static void main(String args[]) { Scanner cin = new Scanner(System.in); int n = cin.nextInt(); int a[] = new int[50]; for(int i=1; i<=n; i++) a[i] = cin.nextInt(); Heapsort(a,n); for(int i=1; i<=n; i++) System.out.print( a[i] + " " ); } } 

     

    快排

     

    import java.io.*; import java.util.*; public class Qsort{ public static int partition(int a[],int p,int r){ int i = p-1; int x = a[r]; int tmp; for(int j=p; j<r; j++) if( a[j] <= x ) { i++; tmp = a[i]; a[i] = a[j]; a[j] = tmp; } tmp = a[i+1]; a[i+1] = a[r]; a[r] = tmp; return i+1; } public static void qsort(int a[],int p,int r){ if( p < r ) { int q = partition(a,p,r); qsort(a,p,q-1); qsort(a,q+1,r); } } public static void main(String args[]){ int a[] = new int[50]; int n; Scanner cin = new Scanner(System.in); n = cin.nextInt(); int i; for(i=1; i<=n; i++) a[i] = cin.nextInt(); qsort(a,1,n); for(i=1; i<=n; i++) System.out.print( "" + ' ' + a[i] ); } }

     

    筛法

     

    public class shaifa{ public static int MAX = 1000001; public static int a[] = new int[MAX]; public static void init(){ int i,j; for(i=1; i<MAX; i++) a[i] = 1; a[0] = a[1] = 0; for(i=2; i<MAX; i++) for(j=2; j*i<MAX; j++) if( a[i] == 1 ) a[j*i] = 0; for(i=1; i<MAX; i++) if( a[i] == 1 ) System.out.print(i+""+' '); } public static void main(String args[]){ init(); } } 


    最新回复(0)