1. Quick sort: First, the simplest Array.sort, sort directly:
public static void main(String[] args) {
int[] arr = {
4,3,5,1,7,9,3};
Arrays.sort(arr);
for (int i : arr){
System.out.println(i);
}
Click run to output the sorted array numbers.
2. Partial sorting method: Using Array.sort, you can also select part of the numbers you want to sort, such as sorting the numbers with subscript numbers 1 to 4, and the order of other numbers remains unchanged.
public static void main(String[] args) {
int[] arr = {
4,3,5,1,2,9,3,0};
Arrays.sort(arr,1,4);
for (int i = 0;i<arr.length;i++){
System.out.print(arr[i]+",");
}
}
The output result is: 4,1,3,5,2,9,3,0, it can be seen that only the numbers with subscripts 1~4 are sorted.
3. Bubble sorting method: As the name suggests, from bottom to top, compare the two pairs, the smaller the more up, so as to form a sorting from small to large.
public static void bubble(int[] arr){
int temp;
//根据角标进行比较,
for(int i = 0; i<arr.length; i++){
//j是数组的最后一个角标
for (int j = arr.length-1; j > i; j--) {
if (arr[j] < arr[j - 1]) {
//从后往前进行比较,小数往前,一轮之后最小数就在最前面了
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int[] arr = {
3,22,5,3,66,2,9};
bubble(arr);
//使用foreach循环输出
for(int x : arr){
System.out.println(x);
}
//使用字符串表达形式输出,输出形式更为直观
System.out.println(Arrays.toString(arr));
}