java选择 冒泡 插入排序


public class SortDemo{
private int[] sortArray;

public SortDemo(){
sortArray=new int[8];
}

public void swap(int i,int j){
int t=sortArray[i];
sortArray[i]=sortArray[j];
sortArray[j]=t;
}

public void insertArray(int pos,int val){
sortArray[pos]=val;
}
/*将数组要比较的首个元素与后面所有元素比较大小,然后不符合要求的进行调换,否则不变。*/
public void selectSort(){
int t,tt;
for(int j=0;j<sortArray.length-1;j++){

for(int i=j+1;i<sortArray.length;i++){

if(sortArray[i]<sortArray[j]) swap(i,j);
}
}
}


/*exchange记录了交换的终点,每次比较都将至少排好一个数,而使在下一次要比较的数至少少一位*/
public void bubbleSort(){
int exchange=sortArray.length;
int bound;
while(exchange!=0){
bound=exchange-1;
exchange=0;
for(int i=0;i<bound;i++){
if(sortArray[i]>sortArray[i+1]){
swap(i,i+1);
exchange=i+1;
}
}
}

}

public void insertSort(){
for(int i=1;i<sortArray.length;i++){
int temp=sortArray[i];
int j=i;
while(j>0&&temp<sortArray[j-1]){
sortArray[j]=sortArray[j-1];
j--;
}
sortArray[j]=temp;
}

}

public void showResult(){
for(int i =0;i<sortArray.length;i++)
System.out.print(sortArray[i]+" ");
System.out.println("");
}

public static void main(String[] args){

SortDemo so=new SortDemo();
so.insertArray(0,2);
so.insertArray(1,23);
so.insertArray(2,22);
so.insertArray(3,12);
so.insertArray(4,42);
so.insertArray(5,32);
so.insertArray(6,62);
so.insertArray(7,52);
so.showResult();
so.selectSort();
so.showResult();
so.bubbleSort();
so.showResult();
so.insertSort();
so.showResult();

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值