冒泡排序的四种变形
程序员文章站
2022-05-12 17:49:32
...
/**
* 冒泡排序法
*/
public void bubbleUp1(Integer[] numberArray){
int loopNumber = 0;
for(int i=0;i<numberArray.length-1;i++){
for(int j=0;j<numberArray.length-1;j++){
if(numberArray[j]>numberArray[j+1]){
swap(numberArray,j,j+1);
}
loopNumber++;
}
}
System.out.println("循环次数:"+loopNumber);
this.printArray(numberArray);
}
public void bubbleUp2(Integer[] numberArray){
int loopNumber =0;
for(int i=0;i<numberArray.length-1;i++){
boolean swapStatus=false;
for(int j=0;j<numberArray.length-1;j++){
if(numberArray[j]>numberArray[j+1]){
this.swap(numberArray,j,j+1);
swapStatus=true;
}
loopNumber++;
}
if(!swapStatus){
break;
}
}
System.out.println("循环次数:"+loopNumber);
this.printArray(numberArray);
}
private Integer[] bubbleUp3(Integer[] numberArray){
int loopNumber =0;
int end = numberArray.length;
for(int i=0;i<numberArray.length-1;i++){
int newEnd=0;
for(int j=0;j<end-1;j++){
if(numberArray[j]>numberArray[j+1]){
this.swap(numberArray,j,j+1);
newEnd=j+1;
}
loopNumber++;
}
end=newEnd;
if(end==0){
break;
}
}
System.out.println("循环次数:"+loopNumber);
return numberArray;
}
private Integer[] bubbleUp4(Integer[] numberArray){
int loopNumber =0;
int begin=0;
int end = numberArray.length;
while(end>=begin) {
int newEnd=begin;
int newBegin=end;
for (int i = begin; i < end-1; i++) {
if (numberArray[i] > numberArray[i + 1]) {
swap(numberArray, i, i + 1);
newEnd=i+1;
}
loopNumber++;
}
end=newEnd-1;
System.out.print(end);
System.out.print("*");
for (int j = end; j > begin - 1; j--) {
if (numberArray[j] > numberArray[j + 1]) {
this.swap(numberArray, j, j + 1);
newBegin=j;
}
loopNumber++;
}
begin=newBegin+1;
System.out.print(begin);
System.out.println();
}
System.out.println("循环次数:" + loopNumber);
return numberArray;
}
private void swap(Integer[] numberArray,int source,int to){
Integer number = numberArray[to];
numberArray[to]=numberArray[source];
numberArray[source]=number;
}
上一篇: 2012年度中国最佳云计算运营商