经典算法之:冒泡排序
以从小到大排序举例:
设数组长度为N
1.从前到后依次比较相邻的数据,如果前面的数据大于后面的数据,就将两个数据进行交换
2.这样对数组的第0个数据到N-1个数据进行一次遍历后,最大的一个数据就"沉"到数组第N-1个位置
java代码:
public class BubleSort {
public int[] bubleSort(int[] A, int n) {
int len = A.length;
for(int i=0;i<len-1;i++){
for(int j=0;j<len-1;j++){
int t;
if(A[j]>A[j+1]){
t = A[j];
A[j] = A[j+1];
A[j+1] = t;
}
}
}
return A;
}
优化版:减少每一趟的次数
public class BubbleSort {
public int[] bubbleSort(int[] A, int n) {
int len = A.length;
for(int i=0;i<len-1;i++){
for(int j=0;j<len-i-1;j++){
int t;
if(A[j]>A[j+1]){
t = A[j];
A[j] = A[j+1];
A[j+1] = t;
}
}
}
return A;
}
最终版:假设数据已经有序,或者经过某趟后有序,减少趟数
如:8 1 2 3 4
第一趟: 1 2 3 4 8
第二趟: 1 2 3 4 5 没有交换停止循环
public class BubbleSort {
public int[] bubbleSort(int[] A) {
boolean sorted = true;
int len = A.length; //假定有序
for(int i=0;i<len-1;i++){
sorted = true;
for(int j=0;j<len-i-1;j++){
int t;
if(A[j]>A[j+1]){
t = A[j];
A[j] = A[j+1];
A[j+1] = t;
sorted = false;
}
}
if (sorted) {
break;
}
}
return A;
}