黑马程序员技术交流社区
标题:
基础程序代码
[打印本页]
作者:
蓝枫
时间:
2014-3-17 09:38
标题:
基础程序代码
打印数组最大值
class Demo
{
public static int getMax(int[] arr)
{
int max =0;
for(int x= 0;x<arr.length;x++)
{
if(arr[x]>max)
max=arr[x];
}
return max;
}
public static void main(String[]args)
{
int[] arr={5,2,8,1,9,3};
int max = getMax(arr);
System.out.println("max="+max);
}
}
打印数组最小值
class Demo
{
public static int getMin(int[] arr)
{
int min = 0;
for(int x = 0;x<arr.length;x++)
{
if(arr[x]<min)
min = arr[x];
}
return min;
}
public static void main(String[] args)
{
int[] arr={5,2,8,1,9,3};
int min = getMin(arr);
System.out.println("min="+min);
}
}
选择排序
class Demo
{
public static void selectSort(int[] arr)
{
for(int x =0; x<arr.length-1;x++)
{
for(int y=x+1;y<arr.length;y++)
{
if(arr[x]>arr[y])
{
int temp = arr[x];
arr[x] = arr[y];
arr[y]=temp;
}
}
}
}
public static void printArray(int[] arr)
{
System.out.print("[");
for(int x =0;x<arr.length;x++)
{
if(x!=arr.length-1)
System.out.print(arr[x]+",");
else
System.out.println(arr[x]+"]");
}
}
public static void main(String[] args)
{
int[] arr={5,2,8,1,9,3};
printArray(arr);
selectSort(arr);
printArray(arr);
}
}
冒泡排序
class Demo
{
public static void bubbleSort(int[] arr)
{
for(int x=0;x<arr.length-1;x++)
{
for(int y=0;y<arr.length-x-1;y++)
{
if(arr[y]>arr[y+1])
{
int temp = arr[y];
arr[y] = arr[y+1];
arr[y+1]=temp;
}
}
}
}
public static void printArray(int[] arr)
{
System.out.print("[");
for(int x =0;x<arr.length;x++)
{
if(x!=arr.length-1)
System.out.print(arr[x]+",");
else
System.out.println(arr[x]+"]");
}
}
public static void main(String[] args)
{
int[] arr={5,2,8,1,9,3};
printArray(arr);
bubbleSort(arr);
printArray(arr);
}
}
复制代码
作者:
学习代码
时间:
2014-3-17 10:24
帮助到了我们这些初学者 谢谢 以后又不懂的 请多指教
作者:
2528870651
时间:
2014-3-17 11:54
嗯 看过了 !!辛苦了
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2