Home > Java > JavaBase > How to sort java array

How to sort java array

Release: 2019-12-26 13:34:00
Original
21429 people have browsed it

How to sort java array

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);//调用方法排序即可
Copy after login

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;
            }
        }
}
Copy after login

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;
	}
Copy after login

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;
	}
Copy after login

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;
			}
		}
	}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template