首页 > 编程语言 >Arrays.sort() in Java with examples

Arrays.sort() in Java with examples

时间:2023-01-01 14:56:23浏览次数:117  
标签:sort arr Java Arrays method array class

https://www.geeksforgeeks.org/arrays-sort-in-java-with-examples/

Array class is a class containing static methods that are used with arrays in order to search, sort, compare, insert elements, or return a string representation of an array. So let us specify the functions first and later onwards we will be discussing the same. They are as follows being present in java.util.Arrays class. Here we will be discussing different plots using the sort() method of the Arrays class.

Arrays.sort() method consists of two variations one in which we do not pass any arguments where it sort down the complete array be it integer array or character array but if we are supposed to sort a specific part using this method of Arrays class then we overload it and pass the starting and last index to the array.

 

Syntax: sort() Method 

Arrays.sort(); 

Syntax: Overloaded sort() Method

  <iframe data-google-container-id="2" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="1" id="google_ads_iframe_/27823234/GFG_Desktop_PostContent_336x280_0" marginheight="0" marginwidth="0" scrolling="no" src="https://8eeb73d3905dad9c6c0af9af8b9d7f66.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="1"></iframe>
public static void sort(int[] arr, int from_Index, int to_Index) ;

Parameters: It takes three parameters as can be perceived from the syntax which is as follows:

  • The array to be sorted
  • The index of the first element, inclusive, to be sorted (Referred to as from_index)
  • The index of the last element, exclusive, to be sorted (Referred to as last_index)

Return Type: NA

Complexity Analysis:

  • Time Complexity: O(N log N)
  • Auxiliary Space: O(1)

Now let us see the implementation of the sort() function across different scenarios of the Arrays class as follows:

Example 1:

  • Java
 
import java.util.Arrays;   class GFG {     public static void main(String args[])     {         int[] arr = { 5, -2, 23, 7, 87, -42, 509 };         System.out.println("The original array is: ");         for (int num : arr) {             System.out.print(num + " ");         }         Arrays.sort(arr);         System.out.println("\nThe sorted array is: ");         for (int num : arr) {             System.out.print(num + " ");         }     } }
Output
The original array is: 
5 -2 23 7 87 -42 509 
The sorted array is: 
-42 -2 5 7 23 87 509 

Time Complexity: O(nlog(n)) as it complexity of arrays.sort() 
Auxilliary Space : O(1)

Example 2:

  • 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[] : "                            + Arrays.toString(arr));     } }
Output <iframe data-google-container-id="3" data-is-safeframe="true" data-load-complete="true" frameborder="0" height="1" id="google_ads_iframe_/27823234/gfg_outstream_incontent_0" marginheight="0" marginwidth="0" scrolling="no" src="https://8eeb73d3905dad9c6c0af9af8b9d7f66.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html" title="3rd party ad content" width="1"></iframe>
Modified arr[] : [6, 7, 9, 13, 21, 45, 101, 102]

Time Complexity: O(N log N)
Auxiliary Space: O(1)

Java-Foundation-Course

Example 3:

  • 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[] : "                            + Arrays.toString(arr));     } }
Output
Modified arr[] : [13, 6, 7, 21, 45, 9, 2, 100]

Time Complexity: O(nlog(n)) as it complexity of arrays.sort()
Auxilliary Space : O(1)

Example 4:

  • 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[] : "                            + Arrays.toString(arr));     } }
Output
Modified arr[] : [100, 45, 21, 13, 9, 7, 6, 2]

Time Complexity: O(nlog(n)) as it complexity of arrays.sort()
Auxilliary Space : O(1)

Example 5:

  • 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",                          "www.geeksforgeeks.org",                          "code.geeksforgeeks.org" };           // Sorts arr[] in ascending order         Arrays.sort(arr);         System.out.println("Modified arr[] : "                            + Arrays.toString(arr));           // Sorts arr[] in descending order         Arrays.sort(arr, Collections.reverseOrder());           // Lastly printing the above array         System.out.println("Modified arr[] :"                            + Arrays.toString(arr));     } }
Output  
Modified arr[] : 
Modified arr[] :[www.geeksforgeeks.org, practice.geeksforgeeks.org, code.geeksforgeeks.org]

Time Complexity: O(nlog(n)) as it complexity of arrays.sort()
Auxilliary Space : O(1)

Now lastly we will be implementing the sort() method to the fullest because here we will be declaring our own defined criteria with the help of the Comparator interface.

Example 6:

  • 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<Student> {     // 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]);     } }
Output
Unsorted
111 bbbb london
131 aaaa nyc
121 cccc jaipur

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

Time Complexity: O(nlog(n)) as it complexity of arrays.sort()
Auxilliary Space : O(1)

Remember: There is a slight difference between Arrays.sort() vs Collections.sort(). Arrays.sort() works for arrays which can be of primitive data type also. Collections.sort() works for objects Collections like ArrayListLinkedList, etc. 

Using the reverse order method: This method will sort the array in the descending. In Java Collections class also provides the reverseOrder() method to sort the array in reverse-lexicographic order.  It does not parse any parameter because static method, so we can invoke it directly by using the class name. it will sort arrays in the ascending order by the sort() method after that the reverse order() method will give us the natural ordering and we will get the sorted array in the descending order.

Syntax:

Arrays.sort(a, Collections.reverseOrder());  

Example 7:

  • Java
 
// This will sort the array in the descending order /*package whatever //do not write package name here */ import java.util.Arrays; import java.util.Collections; public class GFG {     public static void main(String[] args)     {         Integer[] array             = { 99, 12, -8, 12, 34, 110, 0, 121, 66, -110 };           Arrays.sort(array, Collections.reverseOrder());         System.out.println(             "Array in descending order: "             + Arrays.toString(array));     } }
Output
Array in descending order: [121, 110, 99, 66, 34, 12, 12, 0, -8, -110]

Time Complexity: O(nlog(n)) as it complexity of arrays.sort()
Auxilliary Space : O(1)

This article is contributed by Mohit Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.

标签:sort,arr,Java,Arrays,method,array,class
From: https://www.cnblogs.com/kungfupanda/p/17018068.html

相关文章

  • Java集合 - HashMap
    介绍HashMapMap是一种存储键值对的集合。Map集合可以根据key快速查找对应的value值。HashMap是Map类型的一中。HashMap的底层存储结构是:数组+链表+红黑树......
  • JAVAEE零基础小白免费技术教程之集合体系结构讲解
    day13_JAVAOOP课程目标1.【理解】集合的体系结构2.【掌握】Collection集合中常用的方法3.【理解】Iterator迭代器4.【掌握】增强for的使用5.【理解】List集合的......
  • java中的Vector类的add()解析
    示例代码如下:publicclassVectorTest{publicstaticvoidmain(String[]args){Listlist=newVector();//接口的多态for(inti=0;i<10;......
  • JAVA零基础小白免费学习教程之Object类和String类
    day10-JAVAOOP课程目标1.【理解】什么是API2.【掌握】API的使用方式3.【理解】Object类4.【掌握】Object类中的equals方法5.【掌握】String类中的常用方法API......
  • JAVA零基础小白学习教程之StringBuilder类和包装类.Arrays类.Math类
    day11-JAVAOOP课程目标1.【理解】StringBuilder类2.【掌握*】StringBuilder的使用3.【理解】Math类的使用4.【理解】Arrays类的使用5.【掌握*】包装类的使用6.......
  • JAVA零基础小白免费学习教程之异常类和Log4j
    day12_JAVAOOP课程目标1.【理解】什么是异常2.【理解】异常的体系结构3.【掌握】处理异常的方式4.【理解】自定义异常5.【理解】Log4J的作用视频:https://www.b......
  • cmd输入java -version显示could not open `E:\Java\jre\lib\amd64\jvm.cfg'错误
    cmd输入java-version显示couldnotopen`E:\Java\jre\lib\amd64\jvm.cfg'错误方法参照:文献参考每个人出现这种情况,无非两种,一种是环境变量没有配置正确,另一种是......
  • 1.走近Java世界中的线程
    一.基本概念 进程是程序运行的实例。 进程是程序向操作系统申请资源(如内存空间和文件句柄)的基本单位。线程是进程中可独立执行的最小单位。 一个进程中可以包含多个......
  • JavaDoc
    小插曲右键ShowinExplorer:在文件夹中打开类JavaDoc生成API文档,将注释信息生成一个帮助文档,即JavaAPI文档命令行方式:javadoc-encodingUTF-8-charsetUTF......
  • java基础--01
    因为考研大半年没有学java很多基础知识都已经忘了,但是幸好一直在学C语言,作为基础的编程的语言和Java的很多地方还是很像的,特别是一些标识符数据类型表达式什么的,但是java在......