class Test_Array {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
//selectSort(arr);
//bubbleSort(arr);
//printArr(arr);
//int index = getIndex(arr,5);
//int index = ergodicFind(arr,5);
//System.out.println("元素在数组中的第"+index+"位");
//inversion(arr);
//printArr(arr);
}
public static void print(char[] chs,int key) {
System.out.println(chs[key]);
}
public static void inversion(int[] arr) { //数组反转
for (int a = 0;a < arr.length/2 ;a++ ) {
int temp = arr[a];
arr[a] = arr[arr.length-1-a];
arr[arr.length-1-a] = temp;
}
}
public static int getIndex(int[] arr,int key) { //查找角标
for (int a = 0; a < arr.length ;a++ ) {
if(arr[a]==key) {
return a;
}
}
return -1;
}
public static int ergodicFind(int[] arr,int key) { //折半查找
int min = 0;
int max = arr.length-1;
int mid = (max+min)/2;
while (arr[mid]!=key) {
if (key<arr[mid]) {
max = mid-1;
}else if (key>arr[mid]) {
min = mid+1;
}
mid = (max+min)/2;
}
return mid;
}
public static void selectSort(int[] arr) { //选择排序
for ( int a = 0 ;a < arr.length-1 ;a++ ) {
for (int b =a+1;b < arr.length ;b++ ) {
if (arr[a]>arr[b]) {
change(arr,a,b) ;
}
}
}
}
public static void bubbleSort(int[] arr) { //冒泡排序
for ( int a = 0 ;a < arr.length-1 ;a++ ) {
for (int b =0;b < arr.length-a-1 ;b++ ) {
if (arr[b]>arr[b+1]) {
change(arr,b,b+1) ;
}
}
}
}
public static void change(int[] arr,int a,int b) { //数值交换
arr[a] = arr[a] ^ arr[b];
arr[b] = arr[a] ^ arr[b];
arr[a] = arr[a] ^ arr[b];
}
public static void printArr(int[] arr) { //打印数组
for (int x = 0;x < arr.length ;x++ ) {
if (x != arr.length-1) {
System.out.print(arr[x]+",");
}else {
System.out.println(arr[x]);
}
}
}
} |
|