数组 选择排序和冒泡排序

选择排序

每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置

直到全部待排序的数据元素排完。 每次比较仅做一次交换
 

public class 选择排序 {
public static void main(String[] args) {
int[] arr = { 5, 2, 4, 9, 1 };
printArray(arr);
selectSort(arr);
printArray(arr);
}

public static void selectSort(int[] arr) {
for (int x = 0; x < arr.length; x++) {
for (int y = x + 1; y < arr.length - 1; y++) {
if (arr[x] > arr[y]) {
int temp = arr[x];
arr[x] = arr[y];
arr[y] = temp;
}
}
}
}

private static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x != arr.length - 1) {
System.out.print(arr[x] + ",");
} else {
System.out.print(arr[x] + "]");

}
}
}

}

冒泡排序

A: 比较相邻的元素。如果第一个比第二个大,就交换他们两个。

B: 对每一对相邻元素作同样的工作,从开始第一对到结尾的最后一对。
    在这一点,最后的元素应该会是最大的数。

C: 针对所有的元素重复以上的步骤,除了最后一个。

D: 持续每次对越来越少的元素重复上面的步骤,直到没有任何一对数字需要比较。

public class 冒泡排序 {
public static void main(String[] args) {
int[] arr = { 3, 6, 9, 1, 5 };
printArray(arr);
bubbleSort(arr);
printArray(arr);
}


private static void bubbleSort(int[] arr) {

for (int x = 0; x < arr.length - 1; x++) {
for (int y = 0; y < arr.length - x - 1; y++) {
if (arr[y] > arr[y + 1]) {
int temp = arr[y];
arr[y] = arr[y + 1];
arr[y + 1] = temp;
}
}
}

}
private static void printArray(int[] arr) {
System.out.print("[");
for (int x = 0; x < arr.length; x++) {
if (x != arr.length - 1) {
System.out.print(arr[x] + ",");
} else {
System.out.print(arr[x] + "]");

}
}
}

}

posted @ 2016-03-31 12:23  #蒲公英#  阅读(165)  评论(0编辑  收藏  举报