class ArrayDemo
{
public static void main(String[] args)
{
int[] arr = {9,3,2,6,4};
//selSort(arr);
//bubSort(arr);
printArray(arr);
int max = getMax(arr);
int min = getMin(arr);
System.out.println("max="+max+";min="+min);
int index = getIndex(arr, 2);
System.out.println("2的index是:"+index);
int[] ary = {1,3,4,5,6,9};
int index1 = halfSearch1(ary, 6); //折半查找,针对有序的集合
System.out.println(index1);
}
public static int halfSearch1(int[] arr, int key)
{
int min,max,mid;
min = 0;
max = arr.length - 1;
while (min <= max)
{
mid = (max + min) / 2;
if (arr[mid] > key)
{
max = mid - 1;
}
else if (arr[mid] < key)
{
min = mid + 1;
}
else
return mid; //能找到,直接返回
}
return -1; //循环完了还没找到,返回-1.
}
public static int halfSearch(int[] arr, int key)
{
int min,max,mid;
min = 0;
max = arr.length - 1;
mid = (max + min) / 2;
while (arr[mid] != key)
{
if (key > arr[mid])
{
min = mid + 1;
}
else if (key < arr[mid])
{
max = mid - 1;
}
if (min > max)
{
return -1;
}
mid = (max + min) / 2;
}
return mid;
}
public static void printArray(int [] attr)
{
for(int a : attr)
{
System.out.print(a + ",");
}
}
public static void selSort(int[] arr)
{
for (int x=0; x <= arr.length - 1; x++)
{
for (int y = x+1; y <= arr.length - 1; y++)
{
if (arr[x] > arr[y])
{
swap(arr, x, y);
}
}
}
}
public static void bubSort(int[] arr)
{
for (int x = 0; x <= arr.length - 1; x++)
{
for (int y = 0; y <= arr.length - 1 - x - 1; y++)
{
if (arr[y] > arr[y+1])
{
swap(arr, y, y + 1);
}
}
}
}
private static void swap(int[] arr, int x, int y)
{
int tmp = arr[x];
arr[x] = arr[y];
arr[y] = tmp;
}
public static int getMax(int [] arr)
{
int max = arr[0];
for (int x = 0; x < arr.length; x++)
{
if (arr[x] > max)
{
max = arr[x];
}
}
return max;
}
public static int getMin(int [] arr)
{
int min = arr[0];
for (int x = 0; x < arr.length; x++)
{
if (arr[x] < min)
{
min = arr[x];
}
}
return min;
}
public static int getIndex(int [] arr, int key)
{
for (int x = 0; x < arr.length; x++)
{
if (arr[x] == key)
{
return x;
}
}
return -1;
}
}