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();
}
java选择 冒泡 插入排序
最新推荐文章于 2022-04-14 09:40:41 发布