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});
}
}
package 选择排序;
public class NewSelectSort { //标准写法
public static void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = i;
for (int j = i + 1; j < array.length; j++) {
if (array[j] < array[min]) {
min = j;
}
}
if (min != i) { //相等的情况下,就是说 当前第一个就是最小元素,所以不用交换
int temp = array[i];
array[i] = array[min];
array[min] = temp;
}
}
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
selectSort(new int[] { 5, 3, 6, 8, 78, 4, 7, 9, 2 });
}
}
package 选择排序;
public class SelectSort { //自己写的
// 算法: 找出最小值,然后将这个最小值和最前面的数据进行交换位置
// n 个数据需要比较 n-1趟 (每趟将找出来的最小值与当前最前面的值进行交换)
//
public static void selectSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int min = array[i]; // 先假设第一个就是最小的数据
for (int j = i; j < array.length; j++) {
if (array[j] < min) { // 查找最小数据 (需要从当前最前项比较到最后一项 )
int temp = array[j];
array[j] = min;
min = temp;
}
}
array[i] = min; // 将查找的最小数据与当前最前面的数据进行交换
}
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
public static void main(String[] args) {
selectSort(new int[] { 5, 3, 7, 9, 2 });
}
}
package 二分法查找;
public class BinarySearch {
public static void bianySearch(int dest, int[] array) {
int begin = 0;
int end = array.length - 1;
while (begin <= end) {
int mid = (begin + end) / 2;
if(array[mid]==dest){ //切记是 当前中间元素 与 目标查找元素比较!!!!
System.out.println(dest +"在数组中的下标是: "+mid);
return;
}else if(array[mid]<dest){
begin = mid+1;
}else if(array[mid]>dest){
end = mid-1;
}
}
System.out.println("未在数组中找到: "+dest);
}
public static void main(String[] args) {
bianySearch(30, new int[]{1,5,6,9,10,15,17,19,20,30});
}
}