一、基本查找
package com.itheima.d8_sort_binarysearch; /** *基本查找 */ import java.util.Scanner; public class Test3 { public static void main(String[] args) { //1、定义一个数组(基本查找) int[] arr = {12,95,1,3,76,4,2,93,56,49,67}; search(arr); } public static void search(int[] arr){ Scanner sc = new Scanner(System.in); int input = sc.nextInt(); //2、开始查找 for (int i = 0; i < arr.length; i++) { if (arr[i] == input){ System.out.println("索引:"+ i); } } } }
二、选择排序
package com.itheima.d8_sort_binarysearch; import java.util.Arrays; /** * 目标:学会使用选择排序的方法对数组进行排序 */ public class Test1 { public static void main(String[] args) { //1、定义数组 int[] arr = {5 ,1 ,2 ,3}; // 0 1 2 3 //2、定义一个循环控制选择几轮: arr.length() - 1 for (int i = 0; i < arr.length - 1; i++) { // i = 0, j = 1 2 3 //i = 1, j = 2 , 3 //i = 2, j = 3 //3、定义内部循环,控制选择几次 for (int j = i + 1; j < arr.length; j++) { // 当前位:arr[i] // 如果有比当前位数据更小的,则交换 if(arr[i] > arr[j]){ int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } } System.out.println(Arrays.toString(arr)); } }
三、二分查找
package com.itheima.d8_sort_binarysearch; import java.util.Scanner; public class Test2 { public static void main(String[] args) { int[] arr = {1,12,23,34,45,56,79,97}; Scanner scanner = new Scanner(System.in); int data = scanner.nextInt(); System.out.println(binarySearch(arr, data)); } public static int binarySearch(int[] arr , int data){ //1、定义左边位置 和 右边位置 int left = 0; int right = arr.length - 1; //2、开始循环,折半查询 while(left <= right){ //取中间索引 int middleIndex = (left + right ) / 2; //3、判断当前中间位置的元素和要找的元素的大小情况 if(data > arr[middleIndex]){ // 往右边找,左边更新 = 中间索引 + 1 left = middleIndex + 1; }else if(data < arr[middleIndex]){ //往左边找,右边更新为 = 中间位置 - 1 right = middleIndex - 1; }else { return middleIndex; } } return -1;//查无此元素。 } }
标签:二分,arr,Java,Scanner,int,System,查找,public From: https://www.cnblogs.com/liandaozhanshi/p/17478683.html