一:冒泡排序
public class 排序 {
public static void main(String[] args) {
int[] array = new int[1000];
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
for (int i = 1; i < n - 1; i++) {
for (int j = 0; j < n - i; j++) {
if (array[j] > array[j + 1]) {
int temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
if (i < n - 1)
System.out.print(array[i] + ",");
else
System.out.print(array[i]);
}
}
}
二.利用Arrays进行排序
Arrays.sort(数组名,起始位置,终止位置)
public static void main(String[] args) {
int[] array = new int[1000];
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
Arrays.sort(array,0,n);
for(int i=0;i<n;i++)
{
System.out.println(array[i]+" ");
}
}
利用Array.sort()排列,Array.toString()输出
public static void main(String[] args) {
int[] array = new int[1000];
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] a = new int[n];
//因为Array.sort(数组名)默认从最初位置排到最后一位,所有长度应定为n
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
a[i] = array[i];
}
Arrays.sort(a);
//out.println(Arrays.toString(a)直接输出a中全部元素
System.out.println(Arrays.toString(a));
}
三.快速排序
import java.util.Scanner;
public class QuickSort {
public static void main(String[] args) {
int [] num = new int[1000];
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
num[i] = sc.nextInt();
}
QuickSort(num,0,n-1);
for(int i =0;i<n;i++)
{
System.out.print(num[i]+" ");
}
}
private static void QuickSort(int[] num, int left, int right) {
if(left>=right) {
return;
}
int key=num[left];
int i=left;
int j=right;
while(i<j){
while(num[j]>=key && i<j){
j--;
}
while(num[i]<=key && i<j){
i++;
}
if(i<j){
int temp=num[i];
num[i]=num[j];
num[j]=temp;
}
}
num[left]=num[i];
num[i]=key;
QuickSort(num,left,i-1);
QuickSort(num,i+1,right);
}
}