📜  Java中的 Arrays.sort() 示例

📅  最后修改于: 2022-05-13 01:55:02.285000             🧑  作者: Mango

Java中的 Arrays.sort() 示例

数组类是包含静态方法的类,这些静态方法与数组一起使用,以便搜索、排序、比较、插入元素或返回数组的字符串表示形式。在一个数组中。因此,让我们首先指定功能,然后我们将讨论相同的功能。它们如下存在于Java.util.Arrays 类中。在这里,我们将使用 Arrays 类的 sort() 方法讨论不同的绘图。

Arrays.sort() 方法由两种变体组成,一种是我们不传递任何参数,它对整个数组进行排序,无论是整数数组还是字符数组,但是如果我们应该使用 Arrays 类的这种方法对特定部分进行排序,那么我们重载它并将开始和最后一个索引传递给数组。

语法: sort() 方法

Arrays.sort(); 

语法:重载的 sort() 方法

public static void sort(int[] arr, int from_Index, int to_Index) ;

参数:它需要三个参数,从语法中可以看出,如下所示:

  • 要排序的数组
  • 要排序的第一个元素的索引(包括)(称为 from_index)
  • 要排序的最后一个元素的索引,排他性(称为last_index)

返回类型:不返回任何值。

现在让我们看下 Arrays 类不同场景下 sort()函数的实现,如下所示:

示例 1:

Java
// Java Program to Sort Array of Integers
// by Default Sorts in an Ascending Order
// using Arrays.sort() Method
 
// Importing Arrays class from the utility class
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        int[] arr = { 13, 7, 6, 45, 21, 9, 101, 102 };
 
        // Applying sort() method over to above array
        // by passing the array as an argument
        Arrays.sort(arr);
 
        // Printing the array after sorting
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}


Java
// Java program to Sort a Subarray in Array
// Using Arrays.sort() method
 
// Importing Arrays class from java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        // It contains 8 elements as follows
        int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
 
        // Sort subarray from index 1 to 4, i.e.,
        // only sort subarray {7, 6, 45, 21} and
        // keep other elements as it is.
        Arrays.sort(arr, 1, 5);
 
        // Printing the updated array which is
        // sorted after 2 index inclusive till 5th index
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}


Java
// Java program to Sort a Subarray in Descending order
// Using Arrays.sort()
 
// Importing Collections class and arrays classes
// from java.util package
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Note that we have Integer here instead of
        // int[] as Collections.reverseOrder doesn't
        // work for primitive types.
        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
 
        // Sorts arr[] in descending order using
        // reverseOrder() method of Collections class
        // in Array.sort() as an argument to it
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Printing the array as generated above
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}


Java
// Java program to sort an array of strings
// in ascending and descending alphabetical order
// Using Arrays.sort()
 
// Importing arrays and Collections class
// from java.util class
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String arr[] = { "practice.geeksforgeeks.org",
                         "quiz.geeksforgeeks.org",
                         "code.geeksforgeeks.org" };
 
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
 
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Lastly printing the above array
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
    }
}


Java
// Java program to demonstrate Working of
// Comparator interface
 
// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
 
// Class 1
// A class to represent a student.
class Student {
    int rollno;
    String name, address;
 
    // Constructor
    public Student(int rollno, String name, String address)
    {
        // This keyword refers to current object itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
 
    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
 
// Class 2
// Helper class extending Comparator interface
class Sortbyroll implements Comparator {
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        Student[] arr
            = { new Student(111, "bbbb", "london"),
                new Student(131, "aaaa", "nyc"),
                new Student(121, "cccc", "jaipur") };
 
        System.out.println("Unsorted");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
 
        // Sorting on basic as per class 1 created
        // (user-defined)
        Arrays.sort(arr, new Sortbyroll());
 
        System.out.println("\nSorted by rollno");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}


输出:

Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

示例 2:

Java

// Java program to Sort a Subarray in Array
// Using Arrays.sort() method
 
// Importing Arrays class from java.util package
import java.util.Arrays;
 
// Main class
public class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input array
        // It contains 8 elements as follows
        int[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
 
        // Sort subarray from index 1 to 4, i.e.,
        // only sort subarray {7, 6, 45, 21} and
        // keep other elements as it is.
        Arrays.sort(arr, 1, 5);
 
        // Printing the updated array which is
        // sorted after 2 index inclusive till 5th index
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

输出:

Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]

示例 3:

Java

// Java program to Sort a Subarray in Descending order
// Using Arrays.sort()
 
// Importing Collections class and arrays classes
// from java.util package
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Note that we have Integer here instead of
        // int[] as Collections.reverseOrder doesn't
        // work for primitive types.
        Integer[] arr = { 13, 7, 6, 45, 21, 9, 2, 100 };
 
        // Sorts arr[] in descending order using
        // reverseOrder() method of Collections class
        // in Array.sort() as an argument to it
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Printing the array as generated above
        System.out.println("Modified arr[] : %s",
                           Arrays.toString(arr));
    }
}

输出:

Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]

示例 4:

Java

// Java program to sort an array of strings
// in ascending and descending alphabetical order
// Using Arrays.sort()
 
// Importing arrays and Collections class
// from java.util class
import java.util.Arrays;
import java.util.Collections;
 
// Main class
public class GFG {
   
    // Main driver method
    public static void main(String[] args)
    {
        // Custom input string
        String arr[] = { "practice.geeksforgeeks.org",
                         "quiz.geeksforgeeks.org",
                         "code.geeksforgeeks.org" };
 
        // Sorts arr[] in ascending order
        Arrays.sort(arr);
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
 
        // Sorts arr[] in descending order
        Arrays.sort(arr, Collections.reverseOrder());
 
        // Lastly printing the above array
        System.out.println("Modified arr[] : \n%s\n\n",
                           Arrays.toString(arr));
    }
}

输出:

Modified arr[] : 


Modified arr[] : 
[quiz.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]

现在最后我们将充分实现 sort() 方法,因为在这里我们将在 Comparator 接口的帮助下声明我们自己定义的标准。

示例 5:

Java

// Java program to demonstrate Working of
// Comparator interface
 
// Importing required classes
import java.io.*;
import java.lang.*;
import java.util.*;
 
// Class 1
// A class to represent a student.
class Student {
    int rollno;
    String name, address;
 
    // Constructor
    public Student(int rollno, String name, String address)
    {
        // This keyword refers to current object itself
        this.rollno = rollno;
        this.name = name;
        this.address = address;
    }
 
    // Used to print student details in main()
    public String toString()
    {
        return this.rollno + " " + this.name + " "
            + this.address;
    }
}
 
// Class 2
// Helper class extending Comparator interface
class Sortbyroll implements Comparator {
    // Used for sorting in ascending order of
    // roll number
    public int compare(Student a, Student b)
    {
        return a.rollno - b.rollno;
    }
}
 
// Class 3
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        Student[] arr
            = { new Student(111, "bbbb", "london"),
                new Student(131, "aaaa", "nyc"),
                new Student(121, "cccc", "jaipur") };
 
        System.out.println("Unsorted");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
 
        // Sorting on basic as per class 1 created
        // (user-defined)
        Arrays.sort(arr, new Sortbyroll());
 
        System.out.println("\nSorted by rollno");
 
        for (int i = 0; i < arr.length; i++)
            System.out.println(arr[i]);
    }
}

输出:

Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

Sorted by rollno
111 bbbb london
121 cccc jaipur
131 aaaa nyc