冒泡排序
package sort;
public class BubbleSort {
public void bubble() {
int temp = 0;// 临时变量
int a[] = { 15, 23, 6, 9, 89, 26, 77 };
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println("排序前的数组");
// 核心代码
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]) {
// 交换啊a[j]和a[j+1]
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] + "\t");
}
System.out.println("排序后的数组");
}
public static void main(String[] args) {
new BubbleSort().bubble();
}
}
选择排序
package sort;
public class BubbleSort {
public void bubble() {
int temp = 0;// 临时变量
int a[] = { 15, 23, 6, 9, 89, 26, 77 };
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println("排序前的数组");
// 核心代码
for (int i = 0; i < a.length - 1; i++) {
int k = i;// 默认第一个最小
for (int j = i + 1; j < a.length; j++) {
if (a[k] > a[j]) {
k = j;
}
}
if (i != k) {
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
// 打印数组
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println("排序后的数组");
}
public static void main(String[] args) {
new BubbleSort().bubble();
}
}
折半查找
package sort;
import java.util.Scanner;
//先排序数组再查找
public class SelectionSort {
int a[] = { 15, 23, 6, 9, 89, 26, 77 };
// 选择排序
public void selecyion() {
int temp = 0;// 临时变量
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println("排序前的数组");
// 核心代码
for (int i = 0; i < a.length - 1; i++) {
int k = i;// 默认第一个最小
for (int j = i + 1; j < a.length; j++) {
if (a[k] > a[j]) {
k = j;
}
}
if (i != k) {
temp = a[i];
a[i] = a[k];
a[k] = temp;
}
}
// 打印数组
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println("排序后的数组");
}
// 折半查找
public int findmid(int key) {
// 数组排序
selecyion();
int start = 0;// 起始下标
int end = a.length - 1;// 结束下标
int mid = (start + end) / 2;// 取中间位置去比较
// 判断是否和中间位置是否相等,不相等就循环
while (a[mid] != key) {
if (key > a[mid]) {
start = mid + 1;
} else {
end = mid - 1;
}
mid = (end + start) / 2;
// 当起始下标大于结束下标则结束,返回0
if (start > end) {
System.out.println("数组中暂无此数");
return 0;
}
}
System.out.println(key + "在数组中的下标为" + mid);
// 返回中间位置
return mid;
}
public static void main(String[] args) {
// 从控制台读取要查询的数字
Scanner sc = new Scanner(System.in);
int str = sc.nextInt();
new SelectionSort().findmid(str);
}
}