package cn.com;
/**
* @author ty
* @createdate 2013-7-6 下午10:31:29
* @Description: 冒泡排序 内层:数组从头到尾两两比较,如果前小于后,则位置不变;如果前大于后则交换位置。外层:需要比较数组长度-1次
*/
public class BubbleSort {
public static void main(String[] args) {
int[] a = { 1111, 102, 2, 7, 5, 9, 6, 3, 6, 0, 33, 46, 32 };
print(a);
sort(a);
print(a);
}
private static void sort(int[] a) {
for (int k = 0; k < a.length - 1; k++) {
for (int i = 0; i < a.length - 1 - k; i++) {
if (a[i] > a[i + 1]) {
exchange(a, i, i + 1);
}
}
}
}
// 交换两个数在数组中的位置
public static void exchange(int[] a, int start, int old) {
int num = a[start];
a[start] = a[old];
a[old] = num;
}// angelStyle
// 打印
public static void print(int a[]) {
StringBuffer stringBuffer = new StringBuffer();
for (int k : a) {
stringBuffer.append(k + ",");
}
System.out.println(stringBuffer.substring(0, stringBuffer.length() - 1));
}
}
/**
* @author ty
* @createdate 2013-7-6 下午10:31:29
* @Description: 冒泡排序 内层:数组从头到尾两两比较,如果前小于后,则位置不变;如果前大于后则交换位置。外层:需要比较数组长度-1次
*/
public class BubbleSort {
public static void main(String[] args) {
int[] a = { 1111, 102, 2, 7, 5, 9, 6, 3, 6, 0, 33, 46, 32 };
print(a);
sort(a);
print(a);
}
private static void sort(int[] a) {
for (int k = 0; k < a.length - 1; k++) {
for (int i = 0; i < a.length - 1 - k; i++) {
if (a[i] > a[i + 1]) {
exchange(a, i, i + 1);
}
}
}
}
// 交换两个数在数组中的位置
public static void exchange(int[] a, int start, int old) {
int num = a[start];
a[start] = a[old];
a[old] = num;
}// angelStyle
// 打印
public static void print(int a[]) {
StringBuffer stringBuffer = new StringBuffer();
for (int k : a) {
stringBuffer.append(k + ",");
}
System.out.println(stringBuffer.substring(0, stringBuffer.length() - 1));
}
}