冒泡排序(BubbleSort)
import java.util.Scanner;
import java.util.Arrays;
public class BubbleSort
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入数组长度: ");
int[] arr = new int[sc.nextInt()];
System.out.print("请输入数组元素: ");
for (int i = 0;i < arr.length ;i++ )
{
arr[i] = sc.nextInt();
}
int temp;
for (int i = 0;i<arr.length ;i++ )
{
for (int j = 0;j<arr.length-i-1;j++ )
{
if (arr[j]>arr[j+1])
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("由小到大排序结果: " + Arrays.toString(arr));
}
}
选择排序(SelectionSort)
import java.util.Scanner;
import java.util.Arrays;
public class SelectionSort
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print("请输入数组长度: ");
int[] arr = new int[sc.nextInt()];
System.out.print("请输入数组元素: ");
for ( int i = 0;i<arr.length ;i++ )
{
arr[i] = sc.nextInt();
}
int temp;
for (int i = 0;i < arr.length ;i++ )
{
for (int j = i; j< arr.length -1 ;j++ )
{
if (arr[i]>arr[j+1])
{
temp = arr[i];
arr[i] = arr[j+1];
arr[j+1] = temp;
}
}
}
System.out.println("从小到大排序后的数组: "+ Arrays.toString(arr));
}
}
Arrays工具类排序
import java.util.Arrays;
public class Sorts
{
public static void main(String[] args)
{
int[] array = new int[]{1,2,4,8,2,4,0};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
}
}