/*
数组的排序问题
*/
public class Demo1 {
public static void main(String[] args) {
int[] arr = {22,44,55,66,11};
//bubbleSort(arr);
selectSort(arr);
print(arr);
//System.out.println(getIndex(arr,44));
}
//冒泡排序
public static void bubbleSort(int[] arr){
for(int i = 0 ;i < arr.length-1;i++){
for(int j = 0;j < arr.length-1;j++){
if(arr[j] < arr[j + 1]){
swap(arr,j,j+1);
}
}
}
}
public static void print(int[] arr){
for(int i = 0 ;i < arr.length;i++){
System.out.println(arr[i]);
}
}
//选择排序
public static void selectSort(int[] arr){
for(int i = 0;i < arr.length - 1;i++){
for(int j = i + 1;j < arr.length;j++){
if(arr[i] > arr[j]){
swap(arr,i,j);
}
}
}
}
//数组反转
public static void swap(int[] arr,int i ,int j){
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
//折半查找
public static int getIndex(int[] arr,int key){
int min = 0;
int max = arr.length - 1;
int mid = (min + max)/2;
while(arr[mid] != key){
if(arr[mid] > key){
max = mid - 1;
}else if(arr[mid] < key) {
min = mid +1;
}
mid = (min + max)/2;
if(min > max){
return -1;
}
}
return mid;
}
}
|
|