package helloworld;
public class HelloWorld {
public static void main(String[] args) {
// 定义一个整型数组,长度为10
int[] nums = new int[10];
//通过循环给数组赋值
for (int i = 0; i < nums.length; i++) {
// 产生10以内的随机数
int x = (int)(Math.random()*10);
nums[i] = x;// 为元素赋值
}
// 使用foreach循环输出数组中的元素
for (int num: nums){
System.out.print(num + " ");
}
bubbleSort(nums);
System.out.println();
for (int num: nums){
System.out.print(num + " ");
}
int index = halfSearch(nums, 5);
System.out.println();
System.out.println(index);
reverseArray(nums);
for (int num: nums){
System.out.print(num + " ");
}
}
/* 选择排序
public static void selectSort(int[] arr){
for(int j=0; j<arr.length-1; j++){
for(int i=j+1; i<arr.length; i++){
if(arr[j]>arr[i]){
int temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
}
}*/
// 冒泡排序
public static void bubbleSort(int[] arr){
for(int j=0; j<arr.length-1; j++){
for(int i=0; i<arr.length-j-1; i++){
if(arr[i]>arr[i+1]){
int temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
}
}
// 折半查找
public static int halfSearch(int[] arr, int key){
int min,mid,max;
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 reverseArray(int[] arr){
for(int start=0,end=arr.length-1;start<end;start++,end--){
swap(arr, start, end);
}
}
public static void swap(int[] arr, int a, int b){
int temp = arr[a];
arr[a] = arr [b];
arr[b] = temp;
}
}
转载于:https://blog.51cto.com/8869176/1867025