数据结构–排序
可以通过理解各个排序算法的不变性来加深对算法的理解
冒泡排序BubbleSort
不变性:out右边的所有数据项都是有序的。out为outer loop外循环体中的变量。
The Point:
for (out = arrLen-1; out > 1; out--) { //outer loop backword
for (in = 0; in < out; in++) { //inner loop forward
if (a[in] > a[in+1]) {
swap(in, in+1);
}
}
}
The Code:
public class BubbleSort {
private static long[] a;
public static void main(String[] args) {
a = new long[]{88, 5, 44, 12, 15, 18, 0, 2};
bubbleSort(a);//sorting and showing the orderly elements
}
//sorting
private static void bubbleSort(long[] a){
int out, in;
int arrLen = a.length;
display(a);//before sorting
for (out = arrLen-1; out > 1; out--) { //outer loop backword
for (in = 0; in < out; in++) { //inner loop forward
if (a[in] > a[in+1]) {
swap(in, in+1);
}
}
}
display(a);//after sorting
}
//swap the elements
private static void swap(int one, int two){
long temp = a[one];
a[one] = a[two];
a[two] = temp;
}
//show the elements
private static void display(long[] a){
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length; i++) {
sb.append(a[i] + " ");
}
System.out.println(sb.toString());
}
}