logo

Како сортирати низ у Јави

Сортирање је начин да се елементи листе или низа распореде по одређеном редоследу. Редослед може бити у растућем или опадајућем редоследу. Тхе бројчане и лексикографски (азбучни) ред је широко коришћен редослед.

У овом одељку ћемо научити како сортирати низ ин Јава ин узлазни и силазни наручите користећи врста() метода и без коришћења методе сорт(). . Уз ово ћемо и научити како сортирати подниз ин Јава .

Сортирај низ у растућем редоследу

Тхе Примање наруџбине распоређује елементе од најнижег до највишег реда. Такође је познато као природни поредак или нумерички редослед . Можемо извршити сортирање на следеће начине:

  • Коришћење методе сорт().
  • Без употребе методе
    • Коришћење фор петље
    • Коришћење методе коју дефинише корисник

Коришћење методе сорт().

у Јави, Низови је класа дефинисана ујава.утилпакет који обезбеђује врста() метод за сортирање низа у растућем редоследу. Користи Дуал-Пивот Куицксорт алгоритам за сортирање. Његова сложеност је О(н лог(н)) . То је статичне метод који анализира ан низ као параметар и не враћа ништа. Можемо га позвати директно користећи име класе. Прихвата низ типа инт, флоат, доубле, лонг, цхар, бите.

Синтакса:

 public static void sort(int[] a) 

Где а је низ да буде кратак.

Напомена: Као и класа Арраис, класа Цоллецтионс такође обезбеђује метод сорт() за сортирање низа. Али постоји разлика између њих. Метода сорт() класе Арраис ради за примитивни тип, док метода сорт() класе Цоллецтионс ради за објекте Цоллецтионс, као што су ЛинкедЛист, АрраиЛист, итд.

Хајде да сортирамо низ помоћу методе сорт() класе Арраис.

У следећем програму смо дефинисали низ типа целих бројева. Након тога, позвали смо метод сорт() класе Арраис и анализирамо низ да би се сортирао. За штампање сортираног низа користили смо фор петљу.

СортАрраиЕкампле1.јава

 import java.util.Arrays; public class SortArrayExample1 { public static void main(String[] args) { //defining an array of integer type int [] array = new int [] {90, 23, 5, 109, 12, 22, 67, 34}; //invoking sort() method of the Arrays class Arrays.sort(array); System.out.println(&apos;Elements of array sorted in ascending order: &apos;); //prints array using the for loop for (int i = 0; i <array.length; i++) { system.out.println(array[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Array elements in ascending order: 5 12 22 23 34 67 90 109 </pre> <p>In the above program, we can also use the toSting() method of the Arrays class to print the array, as shown in the following statement. It returns a string representation of the specified array.</p> <pre> System.out.printf(Arrays.toString(array)); </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an array of integer type and sort the array in ascending order.</p> <p> <strong>SortArrayExample2.java</strong> </p> <pre> public class SortArrayExample2 { public static void main(String[] args) { //creating an instance of an array int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65}; System.out.println(&apos;Array elements after sorting:&apos;); //sorting logic for (int i = 0; i <arr.length; i++) { for (int j="i" + 1; arr[j]) tmp="arr[i];" arr[i]="arr[j];" arr[j]="tmp;" } prints the sorted element of array system.out.println(arr[i]); < pre> <p> <strong>Output:</strong> </p> <pre> Array elements after sorting: -65 -4 -1 1 3 6 20 34 34 55 78 90 </pre> <h3>Using the User Defined Method</h3> <p>In the following example, we have defined a method named <strong>sortArray()</strong> that contains the logic to sort an array in natural order.</p> <p> <strong>SortArrayExample3.java</strong> </p> <pre> public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print('array elements after sorting: 
'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;></pre> <p> <strong>Output:</strong> </p> <pre> Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 </pre> <h2>Sort Array in Descending Order</h2> <p>The <strong>descending order</strong> arranges the elements in the highest to lowest order. We can perform sorting in the following ways:</p> <ul> <li>Using the <strong>reverseOrder()</strong> Method</li> <li>Without using the method <ul> <li>Using the <strong>for</strong> Loop</li> <li>Using the <strong>User Defined</strong> Method</li> </ul></li> </ul> <h3>Using the reverseOrder() Method</h3> <p> <a href="/java-collections-class">Java <strong>Collections</strong> class</a> provides the <strong>reverseOrder()</strong> method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a <strong>comparator</strong> that imposes the reverse of the natural ordering (ascending order).</p> <p>It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Comparator reverseOrder() </pre> <p>Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:</p> <pre> Arrays.sort(a, Collections.reverseOrder()); </pre> <p>Let&apos;s sorts an array in the descending order.</p> <p>In the following program, a point to be noticed that we have defined an array as <strong>Integer</strong> . Because the reverseOrder() method does not work for the primitive data type.</p> <p> <strong>SortArrayExample4.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] </pre> <p>Let&apos;s see another program that sorts array elements in alphabetical order.</p> <p> <strong>SortArrayExample5.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an integer array and perform sorting in descending order.</p> <p> <strong>SortArrayExample6.java</strong> </p> <pre> public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println('array elements in descending order:'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println('array elements in descending order:'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;></pre></arr.length;></pre></array.length;>

У горњем програму такође можемо користити метод тоСтинг() класе Арраис за штампање низа, као што је приказано у следећој изјави. Враћа стринг приказ наведеног низа.

 System.out.printf(Arrays.toString(array)); 

Без употребе методе

Коришћење фор петље

У следећем примеру, ми смо иницијализовали низ целобројног типа и сортирали низ у растућем редоследу.

линук менаџер задатака

СортАрраиЕкампле2.јава

 public class SortArrayExample2 { public static void main(String[] args) { //creating an instance of an array int[] arr = new int[] {78, 34, 1, 3, 90, 34, -1, -4, 6, 55, 20, -65}; System.out.println(&apos;Array elements after sorting:&apos;); //sorting logic for (int i = 0; i <arr.length; i++) { for (int j="i" + 1; arr[j]) tmp="arr[i];" arr[i]="arr[j];" arr[j]="tmp;" } prints the sorted element of array system.out.println(arr[i]); < pre> <p> <strong>Output:</strong> </p> <pre> Array elements after sorting: -65 -4 -1 1 3 6 20 34 34 55 78 90 </pre> <h3>Using the User Defined Method</h3> <p>In the following example, we have defined a method named <strong>sortArray()</strong> that contains the logic to sort an array in natural order.</p> <p> <strong>SortArrayExample3.java</strong> </p> <pre> public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print(\'array elements after sorting: 
\'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;></pre> <p> <strong>Output:</strong> </p> <pre> Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 </pre> <h2>Sort Array in Descending Order</h2> <p>The <strong>descending order</strong> arranges the elements in the highest to lowest order. We can perform sorting in the following ways:</p> <ul> <li>Using the <strong>reverseOrder()</strong> Method</li> <li>Without using the method <ul> <li>Using the <strong>for</strong> Loop</li> <li>Using the <strong>User Defined</strong> Method</li> </ul></li> </ul> <h3>Using the reverseOrder() Method</h3> <p> <a href="/java-collections-class">Java <strong>Collections</strong> class</a> provides the <strong>reverseOrder()</strong> method to sort the array in reverse-lexicographic order. It is a static method, so we can invoke it directly by using the class name. It does not parse any parameter. It returns a <strong>comparator</strong> that imposes the reverse of the natural ordering (ascending order).</p> <p>It means that the array sorts elements in the ascending order by using the sort() method, after that the reverseOrder() method reverses the natural ordering, and we get the sorted array in descending order.</p> <p> <strong>Syntax:</strong> </p> <pre> public static Comparator reverseOrder() </pre> <p>Suppose, a[] is an array to be sort in the descending order. We will use the reverseOrder() method in the following way:</p> <pre> Arrays.sort(a, Collections.reverseOrder()); </pre> <p>Let&apos;s sorts an array in the descending order.</p> <p>In the following program, a point to be noticed that we have defined an array as <strong>Integer</strong> . Because the reverseOrder() method does not work for the primitive data type.</p> <p> <strong>SortArrayExample4.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] </pre> <p>Let&apos;s see another program that sorts array elements in alphabetical order.</p> <p> <strong>SortArrayExample5.java</strong> </p> <pre> import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } </pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] </pre> <h3>Without Using the Method</h3> <h3>Using the for Loop</h3> <p>In the following example, we have initialized an integer array and perform sorting in descending order.</p> <p> <strong>SortArrayExample6.java</strong> </p> <pre> public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println(\'array elements in descending order:\'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;></pre></arr.length;>

Коришћење методе коју дефинише корисник

У следећем примеру дефинисали смо метод под називом сортАрраи() који садржи логику за сортирање низа у природном редоследу.

СортАрраиЕкампле3.јава

 public class SortArrayExample3 { public static void main(String[] args) { int i; //initializing an array int array[] = {12, 45, 1, -1, 0, 4, 56, 23, 89, -21, 56, 27}; System.out.print(&apos;Array elements before sorting: 
&apos;); for(i = 0; i <array.length; i++) system.out.println(array[i]); invoking user defined method sortarray(array, array.length); system.out.print(\'array elements after sorting: 
\'); accessing of the sorted array for(i="0;" i <array.length; { } to sort an in ascending order private static void sortarray(int array[], int n) for (int <n; j="i;" a="array[i];" while ((j> 0) &amp;&amp; (array[j-1] &gt; a)) //returns true when both conditions are true { array[j] = array[j-1]; j--; } array[j] = a; } } } </array.length;>

Излаз:

 Array elements before sorting: 12 45 1 -1 0 4 56 23 89 -21 56 27 Array elements after sorting: -21 -1 0 1 4 12 23 27 45 56 56 89 

Сортирај низ у опадајућем редоследу

Тхе силазним редоследом распоређује елементе од највишег до најнижег реда. Можемо извршити сортирање на следеће начине:

  • Помоћу Обрнути редослед() Метод
  • Без употребе методе
    • Помоћу за Лооп
    • Помоћу Усер Дефинед Метод

Коришћење методе реверсеОрдер().

Јава Збирке класа обезбеђује Обрнути редослед() метод за сортирање низа у обрнутом лексикографском редоследу. То је статичан метод, тако да га можемо директно позвати користећи име класе. Не анализира ниједан параметар. Враћа а компаратор то намеће обрнуто од природног поретка (узлазни ред).

То значи да низ сортира елементе по растућем редоследу коришћењем методе сорт() , након тога метода реверсеОрдер() обрће природни редослед, а ми добијамо сортирани низ у опадајућем редоследу.

Синтакса:

 public static Comparator reverseOrder() 

Претпоставимо да је а[] низ који треба сортирати у опадајућем редоследу. Користићемо метод реверсеОрдер() на следећи начин:

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

Хајде да сортирамо низ у опадајућем редоследу.

У следећем програму, треба приметити да смо дефинисали низ као Интегер . Зато што метода реверсеОрдер() не ради за примитивни тип података.

СортАрраиЕкампле4.јава

колико недеља у месецу
 import java.util.Arrays; import java.util.Collections; public class SortArrayExample4 { public static void main(String[] args) { Integer [] array = {23, -9, 78, 102, 4, 0, -1, 11, 6, 110, 205}; // sorts array[] in descending order Arrays.sort(array, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(array)); } } 

Излаз:

 Array elements in descending order: [205, 110, 102, 78, 23, 11, 6, 4, 0, -1, -9] 

Хајде да видимо још један програм који сортира елементе низа по абецедном реду.

јава ретурн низ

СортАрраиЕкампле5.јава

 import java.util.Arrays; import java.util.Collections; public class SortArrayExample5 { public static void main(String[] args) { String [] strarray = {&apos;Mango&apos;, &apos;Apple&apos;, &apos;Grapes&apos;, &apos;Papaya&apos;, &apos;Pineapple&apos;, &apos;Banana&apos;, &apos;Orange&apos;}; // sorts array[] in descending order Arrays.sort(strarray, Collections.reverseOrder()); System.out.println(&apos;Array elements in descending order: &apos; +Arrays.toString(strarray)); } } 

Излаз:

 Array elements in descending order: [Papaya, Pineapple, Orange, Mango, Grapes, Banana, Apple] 

Без употребе методе

Коришћење фор петље

У следећем примеру смо иницијализовали низ целих бројева и извршили сортирање у опадајућем редоследу.

СортАрраиЕкампле6.јава

 public class SortArrayExample6 { public static void main(String[] args) { int temp; //initializing an array int a[]={12,5,56,-2,32,2,-26,9,43,94,-78}; for (int i = 0; i <a.length; i++) { for (int j="i" + 1; < a.length; j++) if (a[i] a[j]) temp="a[i];" a[i]="a[j];" a[j]="temp;" } system.out.println(\'array elements in descending order:\'); accessing element of the array i="0;" - system.out.println(a[i]); pre> <p> <strong>Output:</strong> </p> <pre> Array elements in descending order: 94 56 43 32 12 9 5 2 -2 -26 -78 </pre> <h3>Using the User Defined Method</h3> <p> <strong>SortArrayExample7.java</strong> </p> <pre> import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;></pre></a.length;>

Коришћење методе коју дефинише корисник

СортАрраиЕкампле7.јава

 import java.util.Scanner; public class SortArrayExample7 { public static void main(String[] args) { int n, temp; Scanner s = new Scanner(System.in); System.out.print(&apos;Enter the number of elements: &apos;); n = s.nextInt(); int a[] = new int[n]; System.out.println(&apos;Enter the elements of the array: &apos;); for (int i = 0; i <n; i++) { a[i]="s.nextInt();" } for (int i="0;" < n; j="i" + 1; j++) if (a[i] a[j]) temp="a[i];" a[j]="temp;" system.out.println(\'array elements in descending order:\'); n - system.out.println(a[i]); system.out.print(a[n 1]); pre> <p> <strong>Output:</strong> </p> <pre> Enter the number of elements: 7 Enter the elements of the array: 12 5 56 -2 32 2 -26 Array elements in descending order: 56 32 12 5 2 -2 -26 </pre> <h2>How to Sort Subarray</h2> <p>An array derived from the array is known as <strong>subarray</strong> . Suppose, <strong>a[]</strong> is an array having the elements [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] and we want to sort array elements from 34 to 18. It will sort the subarray <strong>[34, 2, 45, 3, 22, 18]</strong> and keep the other elements as it is.</p> <p>To sort the subarray, the Arrays class provides the static method named <strong>sort()</strong> . It sorts the specified range of the array into ascending order. We can also sort the array of type <strong>long, double, float, char, byte,</strong> etc.</p> <p> <strong>Syntax:</strong> </p> <pre> public static void sort(int[] a, int fromIndex, int toIndex) </pre> <p>The method parses the following three parameters:</p> <ul> <tr><td>a:</td> An array to be sort. </tr><tr><td>fromIndex:</td> The index of the first element of the subarray. It participates in the sorting. </tr><tr><td>toIndex:</td> The index of the last element of the subarray. It does not participate in the sorting. </tr></ul> <p>If formIndex is equal to the toIndex, the range to be sorted is empty. It throws IllegalArgumentException if <strong>fomIndex is greater than toIndex</strong> . It also throws ArrayIndexOutOfBoundsException if <strong>fromIndex a.length</strong> .</p> <p>Let&apos;s sort a subarray through a Java program.</p> <p> <strong>SortSubarrayExample.java</strong> </p> <pre> import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;></pre></n;>

Како сортирати подниз

Низ изведен из низа је познат као подниз . Претпоставимо, а[] је низ који има елементе [12, 90, 34, 2, 45, 3, 22, 18, 5, 78] и желимо да сортирамо елементе низа од 34 до 18. Он ће сортирати подниз [34, 2, 45, 3, 22, 18] а остале елементе задржите онаквима какви јесу.

За сортирање подниза, класа Арраис обезбеђује статички метод под називом врста() . Она сортира наведени опсег низа у растућем редоследу. Такође можемо сортирати низ типа дугачак, двоструки, плутајући, цхар, бајт, итд.

Синтакса:

 public static void sort(int[] a, int fromIndex, int toIndex) 

Метод анализира следећа три параметра:

    а:Низ за сортирање.фромИндек:Индекс првог елемента подниза. Учествује у сортирању.тоИндек:Индекс последњег елемента подниза. Не учествује у сортирању.

Ако је формИндек једнак тоИндек-у, опсег који треба сортирати је празан. Избацује ИллегалАргументЕкцептион ако фомИндек је већи од тоИндек . Такође избацује АрраиИндекОутОфБоундсЕкцептион иф фромИндек а.ленгтх .

Хајде да сортирамо подниз кроз Јава програм.

СортСубарраиЕкампле.јава

 import java.util.Arrays; public class SortSubarrayExample { public static void main(String[] args) { //defining an array int[] a = {12, 90, 34, 2, 45, 3, 22, 18, 5, 78}; // sorts subarray form index 2 to 7 Arrays.sort(a, 2, 7); //prints array using the for loop for (int i = 0; i <a.length; i++) { system.out.println(a[i]); } < pre> <p> <strong>Output:</strong> </p> <pre> Sorted Subarray: 12 90 2 3 22 34 45 18 5 78 </pre> <hr></a.length;>