vlambda博客
学习文章列表

数据结构-折半查找和冒泡排序(Java语言)

package 查找;
import java.util.Scanner;
/** * * @Description * @author qqjl * @version * @date 2021年5月31日下午5:38:38 */public class 折半查找 { public static Scanner scanner = new Scanner(System.in); int[] arr;
public static void main(String[] args) { System.out.println("-------------------------命令菜单-------------------------"); System.out.println("1.建立顺序表 2.顺序表排序 3.二分查找 4.输出顺序表 5.退出"); System.out.print("\n请输入命令:"); int in = scanner.nextInt();
折半查找 j = new 折半查找();
while(true){ if(in < 1 || in > 5) { System.out.print("\n输入命令不存在!请重新输入:"); in = scanner.nextInt(); }else if(in >= 2 && in <= 4) { System.out.print("\n顺序表不存在!请先输入1建立:"); in = scanner.nextInt(); }else{ j.menu(in); } } }
// 判断菜单 public void menu(int n) { switch(n){ case 1: method1(); break; case 2: method2(); break; case 3: method3(); break; case 4: method4(); break; case 5: System.exit(0); break; default: System.out.print("输入命令不存在"); } goon(); }
// 创建顺序表 public void method1(){ System.out.print("请输入顺序表中元素个数:"); arr = new int[scanner.nextInt()]; for (int i = 0; i < arr.length; i++) { System.out.print("请输入数据[" + i + "]:"); arr[i] = scanner.nextInt(); } System.out.println("顺序表建立成功"); }
// 顺序表冒泡排序 public void method2(){ int m = arr.length - 1; int flag = 1; while (m > 0 && flag == 1) { flag=0; for (int j = 0; j < m; j++) { if (arr[j] > arr[j + 1]) { flag = 1; int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t; } } m--; } System.out.println("顺序表排序完成"); }
//二分查找 public void method3() { method2(); System.out.print("请输入二分查找的数据元素:"); int key = scanner.nextInt(); int low = 0; int high = arr.length; int mid; while (low <= high) { mid = (low + high) / 2; if (key == arr[mid]) { System.out.println("元素查找成功,其所在表中位置为:" + mid); return; } else if (key < arr[mid]) { high = mid - 1; } else { low = mid + 1; } } System.out.println("元素查找不成功"); }
//遍历顺序表元素 public void method4() { System.out.print("顺序表元素:"); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + " "); }    System.out.println(); }
public void goon() { System.out.print("\n请继续输入命令:"); menu(scanner.nextInt()); }}