Foreword:
The integration of several commonly used JAVA array sorting methods.
Method 1: Arrays.sort()
The Arrays.sort() sorting method is the simplest and most commonly used sorting method in java
int []arr1= {45,34,59,55};
Arrays.sort(arr1);//Call the method to sort
Method 2: Bubble Sort
Simply put, bubble sort is the process of repeatedly walking through the sequence to be sorted, comparing two elements at a time, and swapping them if they are in the wrong order. The work of visiting the sequence is repeated until no more exchanges are needed, that is, the sequence has been sorted.
//Compare the element at the i-th position with each element after it, and swap the two elements each time a smaller one is encountered.
//After the element at the i-th position is determined, continue to determine the element at the i+1-th position
int arr2[]= {23,48,12,56,45};
int temp;
for(int i=0;i
{
for(int j=i+1;j
{
if(arr2[i]>arr2[j])
{
temp=arr2[i];
arr2[i]=arr2[j];
arr2[j]=temp;
}
}
}
Method 3: Selection Sort
Find the index of where the smallest element is, then swap that element with the element above the first.
int arr3[]= {23,12,48,56,45};
for(int i=0;i
int tem = i;
//Assign the index of the position of the smallest element in the array starting from i to tem
for(int j=i;j
if(arr3[j]
has=j;
}
}
//The position index of the minimum value starting from i in the array obtained above is tem, and the element in the i-th position is exchanged with this index.
int temp1=arr3[i];
arr3[i]=arr3[tem];
arr3[has]=temp1;
}
Method 4: Reverse the sort
Sort the original array in reverse order
//Swap the element at position i of the array with the element at position arr.length-i-1
int []arr4={23,12,48,56,45};
for(int i=0;i
int tp=arr4[i];
arr4[i]=arr4[arr4.length-i-1];
arr4[arr4.length-i-1]=tp;
}
Method 5: Insertion Sort
int []arr5={23,12,48,56,45};
for (int i = 1; i < arr5.length; i++) {
for (int j = i; j > 0; j--) {
if (arr5[j - 1] > arr5[j]) {//大的放后面
int tmp = arr5[j - 1];
arr5[j - 1] = arr5[j];
arr5[j] = tmp;
}
}
}