黑马程序员技术交流社区
标题:
数组遍历排序的集中经常用法
[打印本页]
作者:
122125241
时间:
2015-7-2 10:36
标题:
数组遍历排序的集中经常用法
/*数组遍历*/
public static void print(int [] arr){
System.out.print("[");
for (int x = 0;x <= arr.length-1 ;x++ )
{
if (x==arr.length-1)
{
System.out.println(arr[x]+"]");
}else{
System.out.print(arr[x]+",");
}
}
}
/*数组获取最大值*/
public static int printMax(int [] arr){
int max =0;
for (int x = 0;x <= arr.length-1 ;x++ )
{
if (arr[x]>max)
{
max = arr[x];
}else{
continue;
}
}
return max;
}
/*数组反转*/
public static void printfz(int [] arr){
for (int x = 0 , y = arr.length-1;x < y ;x++,y--)
{
int temp = arr[x];
arr[x] = arr [y];
arr[y] = temp;
}
System.out.print("[");
for (int z = 0;z <= arr.length-1 ;z++ )
{
if (z==arr.length-1)
{
System.out.println(arr[z]+"]");
}else{
System.out.print(arr[z]+",");
}
}
}
/*数组查找
两个明确:返回值类型:int
参数列表:数组,查那个数 int [] arr,int value(值)*/
public static int printSeek(int [] arr,int value){
for (int x = 0;x <= arr.length-1 ;x++ )
{
if (arr[x]== value)
{
return x;
}else{
continue;
}
}
return -1;
}
/*选择排序*/
public static void methed3(int[] arr) {
for (int z = 0; z < arr.length - 1; z++) {
for (int i = z + 1; i < arr.length; i++) {
if (arr[z] > arr[i]) {
int Result = arr[z];
arr[z] = arr[i];
arr[i] = Result;
}
}
}
System.out.println(Arrays.toString(arr));
}
/*
冒泡排序,重点掌握*/
public static void methed2(int[] arr) {
for (int z = 0; z < arr.length; z++) {
for (int i = 0; i < arr.length - z - 1; i++) {
if (arr[i] > arr[i + 1]) {
int Result = arr[i + 1];
arr[i + 1] = arr[i];
arr[i] = Result;
}
}
}
System.out.println(Arrays.toString(arr));
}
/*数组的二分查找,前提是数组有序的排列*/
public static int methed5(int temp, int[] arr) {
int start = 0;
int end = arr.length - 1;
int mid = (start + end) / 2;
while (temp != arr[mid]) {
if (temp > arr[mid]) {
start = mid + 1;
} else if (temp < arr[mid]) {
end = mid - 1;
} else if (temp == arr[mid]) {
return mid;
}
if (start > end) {
return -1;
}
mid = (start + end) / 2;
}
return mid;
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2