Java如何对整数数组进行排序?

3周前#Java
public class SortArr {

    public static void sortAsc(int[] arr) {
        int temp = 0; //a variable to store temporary value while swapping
        for (int i = 0; i < arr.length-1; i++) { //for loop to hold the current element to be compared
            for (int j = i + 1; j < arr.length; j++) { //for loop to iterate over the other elements
                //to get them compared with the current element 
                if (arr[i] > arr[j]) { //if any of the higher index element is smaller than
                                       //the current element
                    temp = arr[i]; //store the current element to temp
                    arr[i] = arr[j]; //store the smaller element to the lower index position
                    arr[j] = temp; //store the current element to greater index position
                }
            }
        }
    }

    public static void main(String args[]) {
        int array[] = {5, 3, 1};
        System.out.println( "Array values before sorting:");
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i]+ "  ");
        }
        System.out.println();
        sortAsc(array);
        System.out.println( "Array values after sorting:");
        for (int i = 0 ; i < array.length; i++){
            System.out.print(array[i]+ "  ");
        }
    }
}

输出:

Array values before sorting:
5  3  1  
Array values after sorting:
1  3  5 

我一开始知道它比较 5 和 3,然后是 5 和 1,但是它如何比较 1 和 3? 谁能解释一下?

回答
D
Della Douglas
3周前

Java 如何对其进行排序取决于实现。 您可以使用 Arrays.sort(),文档说明如下:

实现注意事项:此实现是一种稳定的、自适应的、迭代的合并排序,当输入数组部分排序时需要的比较少于 n lg(n) 次,同时在输入数组随机排序时提供传统合并排序的性能。 如果输入数组几乎已排序,则实现需要大约 n 次比较。 临时存储要求从用于几乎排序的输入数组的小常量到用于随机排序的输入数组的 n/2 对象引用不等。 该实现在其输入数组中同样利用升序和降序,并且可以在同一输入数组的不同部分利用升序和降序。 它非常适合合并两个或多个排序的数组:简单地连接数组并对结果数组进行排序。 该实现改编自 Tim Peters 的 Python 列表排序 (TimSort)。 它使用了 Peter McIlroy 的“乐观排序和信息理论复杂性”中的技术,在第四届年度 ACM-SIAM 离散算法研讨会论文集中,第 467-474 页,1993 年 1 月。

代码示例:

Integer[] array = {3, 1, 2};
Arrays.sort(array);

您的代码似乎是冒泡排序算法,由于 O(n^2) 平均性能,它通常更容易实现但比其他排序算法慢。

此外,您可以使用调试器逐步查看代码的执行情况。

请注意,对于学习范围之外的代码,最好使用内置的排序 API,而不是如上所示,而不是自己实现。