public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String cout = bufferedReader.readLine();
String[] s = cout.split(" ");
int[] arry = new int[s.length];
for (int i = 0; i < s.length; i++) {
arry[i] = Integer.parseInt(s[i]);
}
bubbleSort(arry);
for (int i : arry) {
System.out.print(i + " ");
}
}
//冒泡排序
public static int[] bubbleSort(int[] a) {
for (int i = a.length - 1; i >= 1; i--) {
for(int j = 0;j<a.length-1;j++){
if (a[j]>a[j+1]) {
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}
}
return a;
}
}
冒泡排序核心思想:从后向前执行,用当前数据和上一个数据进行比较,如果满足条件(大于或者小于),则交换两者位置。
下面是基于冒泡排序的双向冒泡排序:
public class Main {
public static void main(String[] args) throws Exception {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
String cout = bufferedReader.readLine();
String[] s = cout.split(" ");
int[] arry = new int[s.length];
for (int i = 0; i < s.length; i++) {
arry[i] = Integer.parseInt(s[i]);
}
myComparator comparator = new myComparator();
bidirBubbleSort(arry,comparator);
for (int i : arry) {
System.out.print(i + " ");
}
}
/**
* 双向冒泡排序,排序按照从小到大。
* @param inputs 输入的对象。
* @param cp 比较器
*/
public static void bidirBubbleSort(int[] inputs, Comparator<Integer> cp) {
int index;
int limit = inputs.length;
int start = -1 ;
while (start < limit) {
start++;
limit--;
boolean swapped = false;
for (index = start; index < limit; index++) {
int cmp = cp.compare(inputs[index], inputs[index + 1]);
if (cmp > 0) {
swap(inputs, index , index + 1);
swapped = true;
}
}
if (!swapped) {
return;
} else {
swapped = false;
}
for (index = limit; --index >= start;) {
int cmp = cp.compare(inputs[index], inputs[index + 1]);
if (cmp > 0) {
swap(inputs, index, index + 1);
swapped = true;
}
}
if (!swapped) {
return;
}
}
}
/**
* 交换。
* @param objs
* @param i
* @param j
*/
private static void swap(int[] objs, int i, int j) {
int T;
T = objs[i];
objs[i] = objs[j];
objs[j] = T;
}
}
public class myComparator implements Comparator<Integer>{
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o1>o2 ? 1 : o1 < o2 ? -1 :0;
}
}
双向冒泡排序核心思想:和冒泡思想基本一致,双向是左边和右边同时向中间进行循环,当两个引用下标相遇时,排序完成;
1764

被折叠的 条评论
为什么被折叠?



