package 冒泡排序;
public class BubbleSort {
public static void sort(int[] a) {
//方法一
/*for (int i = 0; i < a.length - 1; i++) {
for (int j = 0; j < a.length - 1 - i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}*/
// 方法二
//冒泡排序 : n 个数 需要比较 n-1 趟
//第一趟比较 n-1 次
//往后每趟比较的次数都要 减一
for (int i = a.length-1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (a[j] > a[j + 1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
public static void main(String[] args) {
sort(new int[] { 1, 3, 9, 5, 4 ,10,56,2,7});
}
}
public class Main {
// 选择排序算法
public static void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
// 先假定当前比较趟 最前面的是最小数据,标记最小数据下标为 min
int min = i;
for (int j = i + 1; j < array.length; j++) {
// 通过比较找出最小数据,
// 若找出比之前假定最小数据还小,
// 则将其下标赋值给min
if (array[j] < array[min]) {
min = j;
}
}
// min == i 时,表示未找到比之前假定最小数据还小的数据,所以不需要交换
if (min != i) {
int temp = array[min];
array[min] = array[i];
array[i] = temp;
}
}
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
selectSort(new int[] { 1, 8, 4, 2, 7, 9, 3 });
}
}
public class SelectSort {
// 选择排序算法
//条件:
//建立在已经排序的基础上(从小到大排序)
//数组中没有重复元素
public static int selectSort(int dest, int[] array) {
int begin = 0;
int end = array.length - 1;
while (begin <= end) {
int mid = (begin + end) / 2;
if (array[mid] == dest) {
return mid;
} else if (array[mid] < dest) {
begin = mid + 1;
} else if (array[mid] > dest) {
end = mid - 1;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(selectSort(20000000, new int[] { 1, 3,5,8,9,10,25,88,100000,20000000 }));
}
}