java实现冒泡排序以及二分法查找
import java.util.Scanner;
public class SortAndFind {
boolean HalveFin(int right,int left,int array[],int num)//二分查找
{
int mid;
while (right <= left)
{
mid = (right + left)/2;
if(array[mid] > num)
{
left = mid-1;
}else if(array[mid] < num)
{
right = mid+1;
}else
{
System.out.println("num已找到");
return true;
}
}
return false;
}
static void swap(int array[],int i,int j)//交换两个数
{
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
void SoakSort(int array[])//冒泡排序
{
int flag;
for(int i = 0; i < array.length-1; i++)
{
flag = 0;
for (int j = 0; j < array.length-1-i; j++)
{
if(array[j] > array[j+1])
{
swap(array,j,j+1);
flag = 1;
}
}
if(flag == 0)//flag用来判断如果在一趟冒泡排序后没有任何数交换,说明顺序已经排好,直接结束所有循环。
{
System.out.println("冒泡排序结束");
break;
}
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("请输入数组长度:");
int n = scan.nextInt();
SortAndFind sortAndFind = new SortAndFind();
int[] array=new int[n];
System.out.println("请输入数组array的"+n+"个值");
for (int i = 0 ; i < array.length ;i++)//数组输入
{
array[i] = scan.nextInt();
}
System.out.println("即将进行冒泡排序……");
sortAndFind.SoakSort(array);//冒泡排序
for (int i:array)
{
System.out.print(i+">");
}
System.out.println();
System.out.println("请输入需要从数组array中查找的数num:");
int num = scan.nextInt();
System.out.println("即将进行二分法查找");
boolean bool = sortAndFind.HalveFin(0,array.length-1,array,num);//二分法查找
if(bool)
{
System.out.println("数组才采用二分法已查找到num");
}else
System.out.println("数组中没有num");
}
}
版权声明:本文为rwlvjj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。