[教程]Java冒泡排序

2014-05-03 10:10:53 -0400
/**
 *冒泡排序实例
 */
public class Main
{
static void smallToBig(int[] arr){
int temp;
for (int i=0;i < arr.length - 1;i++)
{
for (int j=0;j < arr.length - 1;j++)
{
if (arr[j] > arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int k=0;k < arr.length;k++)
{
System.out.println(arr[k]);
}
}

static void bigToSmall(int[] arr){
int temp;
for (int i=0;i < arr.length - 1;i++)
{
for (int j=0;j < arr.length - 1;j++)
{
if (arr[j] < arr[j + 1])
{
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int k=0;k < arr.length;k++)
{
System.out.println(arr[k]);
}
}
public static void main(String[] args){
int[] arr={45,89,8,99,58,67,99,66,0,1};
System.out.println("======冒泡排序实例======\n");
System.out.println("--从小到大排序:");
smallToBig(arr);
System.out.println("--从大到小排序:");
bigToSmall(arr);
}
}
«Newer      Older»
Comment:
Name:

Back to home

Subscribe | Register | Login | N