Several methods of sorting arrays in java:
1. Use Arrays.sort() to sort
Arrays. The sort() sorting method is the simplest and most commonly used sorting method in Java.
int []arr1= {45,34,59,55}; Arrays.sort(arr1);//调用方法排序即可
The use of Arrays.sort() is mainly divided into sorting arrays of basic data types and sorting arrays of objects.
2. Bubble sorting
Simply put, bubble sorting is to repeatedly visit the sequence to be sorted and compare two elements at a time. If their order If they make a mistake, swap them over. The work of visiting the array is repeated until no more exchanges are needed, which means that the array has been sorted.
//array[]为待排序数组,n为数组长度 void BubbleSort(int array[], int n) { int i, j, k; for(i=0; i<n-1; i++) for(j=0; j<n-1-i; j++) { if(array[j]>array[j+1]) { k=array[j]; array[j]=array[j+1]; array[j+1]=k; } } }
3. Selection sort
First find the index of the smallest element, and then exchange the element with the first element.
int arr3[]= {23,12,48,56,45}; for(int i=0;i<arr3.length;i++) { int tem=i; //将数组中从i开始的最小的元素所在位置的索引赋值给tem for(int j=i;j<arr3.length;j++) { if(arr3[j]<arr3[tem]) { tem=j; } } //上面获取了数组中从i开始的最小值的位置索引为tem,利用该索引将第i位上的元素与其进行交换 int temp1=arr3[i]; arr3[i]=arr3[tem]; arr3[tem]=temp1; }
4. Reverse sorting
Arrange the original array in reverse order
//将数组第i位上的元素与第arr.length-i-1位上的元素进行交换 int []arr4={23,12,48,56,45}; for(int i=0;i<arr4.length/2;i++) { int tp=arr4[i]; arr4[i]=arr4[arr4.length-i-1]; arr4[arr4.length-i-1]=tp; }
5. Direct insertion sorting
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; } } }
For more java knowledge, please pay attention to the java basic tutorial column.
The above is the detailed content of How to sort java array. For more information, please follow other related articles on the PHP Chinese website!