在程序设计中, 优化往往很重要, 老丑君最近也在学习如何去进行优化,如何去提高程序的运行效率,
下面是我学习过程中写的一个基于冒泡排序可以进行扩展和优化的程序, 如有错误, 还望指出, 谢谢支持。
package cn.laochou.sort;
import cn.laochou.interfaces.Comparable;
import cn.laochou.pojo.User;
import cn.laochou.utils.PrintUtils;
/**
* the utils of sort
*/
public class SortUtils {
/**
* 冒泡排序
* 每跑一趟都是找到当前最大的值, 放到最后面
* gof : strategy pattern
* @param array
* @param <T>
*/
public static <T> T[] bubbleSort(T[] array, Comparable<T> comparable){
// at here this is basic method to implement the bubble sort
/**
* but have some problem , how to optimize the algorithm
*
* now please let us to see an example:
* assume have a array like : {1, 2, 3, 4, 5, 6, 7, 9, 8}
* in this array, we use the bubble sort only the first execute finish the sort
* but our program do something uselessly work. so we need to optimize. we can use a flag
* to judge the before of this array is already ordered.
* however our program also exists insufficient
* assume have array like : {1, 4, 3, 2, 6, 7, 8, 9}
* in this array, we can easy to find the front part is no-ordered
* but the the latter part is ordered, so we can't let program to compare the latter part.
* we can use a position to find the start-index of the latter part.
* our program has already through two optimizations, but we can optimize it again.
* base array {6, 1, 2, 3, 4, 5, 0}
*/
// first optimize
int flag = 0;
// second optimize
int position = 0;
// third optimize
int n = 0;
int len = array.length - 1;
for(int i = 0; i < array.length; i++) {
flag = 0;
for (int j = 0; j < len; j++) {
// to find the max value
if (comparable.compareTo(array[j], array[j + 1]) > 0) {
// array[j] > array[j+1]
T temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
flag = 1;
position = j;
}
}
// flag is zero indicate the array isn't change the index of data.
if (flag == 0) break;
len = position;
for(int j = len; j > n; j--){
// to find the min value
if (comparable.compareTo(array[j], array[j - 1]) == 0){
// array[j] < array[j-1]
T temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
flag = 1;
}
}
n++;
if(flag == 0) break;
}
return array;
}
public static void main(String[] args) {
Integer[] data = {7, 2, 3, 4, 5, 6, 0};
System.out.println(PrintUtils.printTArray(SortUtils.bubbleSort(data, new Comparable<Integer>() {
@Override
public int compareTo(Integer t1, Integer t2) {
if (t1 > t2) {
return 1;
} else {
return 0;
}
}
})));
User[] users = {new User("laochou", 20), new User("yzl", 19), new User("pengpeng", 15)};
System.out.println(PrintUtils.printTArray(SortUtils.bubbleSort(users, new Comparable<User>() {
@Override
public int compareTo(User t1, User t2) {
if (t1.getAge() > t2.getAge()) {
return 1;
} else {
return 0;
}
}
})));
}
}