欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java 分别用二叉树、选择法、冒泡法进行排序

程序员文章站 2022-06-23 09:52:37
package collection;import java.util.List;import java.util.Date;import java.util.ArrayList;import file.Hero;public class HeroNode{public HeroNode leftNode;public HeroNode rightNode;public Object value;public void add(Object v){if(null==v...
package collection;
import java.util.List;
import java.util.Date;
import java.util.ArrayList;
import file.Hero;
public class HeroNode{
	
	public HeroNode leftNode;
	public HeroNode rightNode;
	public Object value;
	
	public void add(Object v){
		if(null==value)
			value = v;
		else{
			if((Integer)value>=(Integer) v){
				if(null==leftNode)
					leftNode = new HeroNode();
				leftNode.add(v);
			}
			else{
				if(null==rightNode)
					rightNode = new HeroNode();
				rightNode.add(v);
			}
		}
	}
	public List<Object> value(){
		List<Object> l = new ArrayList<>();
		if(null!=leftNode)
			l.addAll(leftNode.value());
		l.add(value);
		if(null!=rightNode)
			l.addAll(rightNode.value());
		return l;
	}
	public void xuanze(int a[]){
		int min;
		for(int i=0;i<10;i++){
			
			for(int j=i+1;j<10;j++){
				if(a[i]>=a[j]){
					int t= a[j];
					a[j]=a[i];
					a[i] = t;
				}
			}
		}
		System.out.println("选择法:");
		for(int i=0;i<10;i++){
			System.out.print(a[i]+"\t");
		}
	}
	public void maopao(int a[]){
		for(int j=0;j<10;j++){
		  for(int i=0;i<8;i++){
			 if(a[i]>a[i+1]){
				int t = a[i];
			    a[i]=a[i+1];
			    a[i+1]=t;
			}
		}
		}
		System.out.println("冒泡法:");
		for(int i=0;i<10;i++){
			System.out.print(a[i]+"\t");
		}
	}
	public static void main(String[] args){
		int random[] = new int[10];
		Date now = new Date();
		HeroNode hn = new HeroNode();
		for(int i=0;i<10;i++){
			random[i]=(int)(Math.random()*100);
			System.out.print(random[i]+" ");
		}
		System.out.println();
		long t1 = now.getTime();
		for(int i=0;i<10;i++){
			hn.add(random[i]);
		}
		System.out.println("二叉树法:"+hn.value());

		hn.xuanze(random);
		System.out.println();
		hn.maopao(random);

	
	}
}


本文地址:https://blog.csdn.net/qq_37758122/article/details/107341456