Programming

Java에서 배열 정렬

procodes 2020. 6. 1. 20:47
반응형

Java에서 배열 정렬


지금까지는 임의의 값을 갖는 10 개의 정수 배열로 구성된 프로그램을 만들려고합니다.

그러나 이제 가장 낮은 값에서 가장 높은 값까지 순서대로 정렬 한 다음 화면에 인쇄해야합니다. 어떻게해야합니까?

(작은 프로그램에 대한 코드가 너무 많아서 죄송합니다. 루프에 좋지는 않지만 Java로 작업하기 시작했습니다)

public static void main(String args[])
{
    int [] array = new int[10];

    array[0] = ((int)(Math.random()*100+1));
    array[1] = ((int)(Math.random()*100+1));
    array[2] = ((int)(Math.random()*100+1));
    array[3] = ((int)(Math.random()*100+1));
    array[4] = ((int)(Math.random()*100+1));
    array[5] = ((int)(Math.random()*100+1));
    array[6] = ((int)(Math.random()*100+1));
    array[7] = ((int)(Math.random()*100+1));
    array[8] = ((int)(Math.random()*100+1));
    array[9] = ((int)(Math.random()*100+1));

    System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
    +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " 
    + array[8]+" " + array[9] );        

}

루프는 또한 배우는 데 매우 유용합니다. esp 배열을 사용할 때,

int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
    array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
    System.out.print(array[i] + " ");
System.out.println();

println 전에 라인을 추가하면 배열이 정렬됩니다

Arrays.sort( array );

자신을 구현하여 루프를 이해하는 데 도움이 될 수 있습니다. 이해하기 쉬운 거품 정렬을 참조하십시오.

public void bubbleSort(int[] array) {
    boolean swapped = true;
    int j = 0;
    int tmp;
    while (swapped) {
        swapped = false;
        j++;
        for (int i = 0; i < array.length - j; i++) {
            if (array[i] > array[i + 1]) {
                tmp = array[i];
                array[i] = array[i + 1];
                array[i + 1] = tmp;
                swapped = true;
            }
        }
    }
}

더 나은 같은 큰 목록에 대한 알고리즘이 수행 될 때 물론, 당신은 생산에 사용하지 말아야 이것은 QuickSort머지 소트 에 의해 구현된다Arrays.sort(array)


Arrays.sort () 살펴보기


나는 게으르고 루프를 추가했습니다.

import java.util.Arrays;


public class Sort {
    public static void main(String args[])
    {
        int [] array = new int[10];
        for ( int i = 0 ; i < array.length ; i++ ) {
            array[i] = ((int)(Math.random()*100+1));
        }
        Arrays.sort( array );
        for ( int i = 0 ; i < array.length ; i++ ) {
            System.out.println(array[i]);
        }
    }
}

배열의 길이는 10입니다. i값을에서 0가져 오는 변수 ( ) 가 하나 필요 합니다 9.

for ( int i = 0  ; i < array.length ;   i++ ) 
       ^               ^                   ^
       |               |                   ------  increment ( i = i + 1 )
       |               |
       |               +-------------------------- repeat as long i < 10
       +------------------------------------------ start value of i


Arrays.sort( array );

배열을 정렬하는 라이브러리 메소드입니다.


Arrays.sort(yourArray)

일을 완벽하게 할 것입니다


아래를 보면 오름차순과 내림차순으로 정렬됩니다.

import java.util.Arrays;
import java.util.Collections;

public class SortTestArray {

/**
 * Example method for sorting an Integer array
 * in reverse & normal order.
 */
public void sortIntArrayReverseOrder() {

    Integer[] arrayToSort = new Integer[] {
        new Integer(48),
        new Integer(5),
        new Integer(89),
        new Integer(80),
        new Integer(81),
        new Integer(23),
        new Integer(45),
        new Integer(16),
        new Integer(2)
    };

    System.out.print("General Order is    : ");

    for (Integer i : arrayToSort) {
        System.out.print(i.intValue() + " ");
    }


    Arrays.sort(arrayToSort);

    System.out.print("\n\nAscending Order is  : ");

    for (Integer i : arrayToSort) {
        System.out.print(i.intValue() + " ");
    }


    Arrays.sort(arrayToSort, Collections.reverseOrder());
    System.out.print("\n\nDescinding Order is : ");
    for (Integer i : arrayToSort) {
        System.out.print(i.intValue() + " ");
    }

}


/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    SortTestArray SortTestArray = new SortTestArray();
    SortTestArray.sortIntArrayReverseOrder();
}}

출력은

General Order is    : 48 5 89 80 81 23 45 16 2 

Ascending Order is  : 2 5 16 23 45 48 80 81 89 

Descinding Order is : 89 81 80 48 45 23 16 5 2 

참고 : 수동 번호를 추가하는 대신 Math.ranodm을 사용할 수 있습니다. 코드를 변경해야하는지 알려주십시오.

행운을 빕니다 ... 건배 !!!


프로그램에서 이것을 사용하는 방법은 다음과 같습니다.

public static void main(String args[])
{
    int [] array = new int[10];

    array[0] = ((int)(Math.random()*100+1));
    array[1] = ((int)(Math.random()*100+1));
    array[2] = ((int)(Math.random()*100+1));
    array[3] = ((int)(Math.random()*100+1));
    array[4] = ((int)(Math.random()*100+1));
    array[5] = ((int)(Math.random()*100+1));
    array[6] = ((int)(Math.random()*100+1));
    array[7] = ((int)(Math.random()*100+1));
    array[8] = ((int)(Math.random()*100+1));
    array[9] = ((int)(Math.random()*100+1));

    Arrays.sort(array); 

    System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
    +" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" " 
    + array[8]+" " + array[9] );        

}

참고로 이제 Java 8 새로운 API를 사용하여 모든 유형의 배열을 정렬 할 수 있습니다. parallelSort

parallelSort Java 7에 도입 된 Fork / Join 프레임 워크를 사용하여 스레드 풀에서 사용 가능한 여러 스레드에 정렬 태스크를 지정합니다.

int배열 을 정렬하는 데 사용할 수있는 두 가지 방법

parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)

int[] array = {2, 3, 4, 5, 3, 4, 2, 34, 2, 56, 98, 32, 54};

for (int i = 0; i < array.length; i++) {
    for (int j = 0; j < array.length; j++) {
        if (array[i] < array[j]) {
            int temp = array[i];
            array[i] = array[j];
            array[j] = temp;
        }
    }
}

자연 질서 : Arrays.sort(array)

For reverse Order : Arrays.sort(array, Collections.reverseOrder()); -- > It is a static method in Collections class which will further call an inner class of itself to return a reverse Comparator.


You can sort a int array with Arrays.sort( array ).


Java 8 provides the option of using streams which can be used to sort int[] array as:

int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2

As mentioned in doc for parallelSort :

The sorting algorithm is a parallel sort-merge that breaks the array into sub-arrays that are themselves sorted and then merged. When the sub-array length reaches a minimum granularity, the sub-array is sorted using the appropriate Arrays.sort method. If the length of the specified array is less than the minimum granularity, then it is sorted using the appropriate Arrays.sort method. The algorithm requires a working space no greater than the size of the original array. The ForkJoin common pool is used to execute any parallel tasks.

So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort simply calls sequential sort algorithm.

Just in case we want to reverse sort the integer array we can make use of comparator as:

int[] reverseSorted = IntStream.of(array).boxed()
                        .sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();

Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.


You may use Arrays.sort() function.

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)

MOST EFFECTIVE WAY!

public static void main(String args[])
{
    int [] array = new int[10];//creates an array named array to hold 10 int's
    for(int x: array)//for-each loop!
      x = ((int)(Math.random()*100+1));
    Array.sort(array);
    for(int x: array)
      System.out.println(x+" ");
}

If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :

1- Create sort class

class QuickSort {
    private int input[];
    private int length;

    public void sort(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }
        this.input = numbers;
        length = numbers.length;
        quickSort(0, length - 1);
    }
    /*
     * This method implements in-place quicksort algorithm recursively.
     */

    private void quickSort(int low, int high) {
        int i = low;
        int j = high;

        // pivot is middle index
        int pivot = input[low + (high - low) / 2];

        // Divide into two arrays
        while (i <= j) {
            /**
             * As shown in above image, In each iteration, we will identify a
             * number from left side which is greater then the pivot value, and
             * a number from right side which is less then the pivot value. Once
             * search is complete, we can swap both numbers.
             */
            while (input[i] < pivot) {
                i++;
            }
            while (input[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                // move index to next position on both sides
                i++;
                j--;
            }
        }

        // calls quickSort() method recursively
        if (low < j) {
            quickSort(low, j);
        }

        if (i < high) {
            quickSort(i, high);
        }
    }

    private void swap(int i, int j) {
        int temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
}

2- Send your unsorted array to Quicksort class

import java.util.Arrays;


public class QuickSortDemo {

    public static void main(String args[]) {
        // unsorted integer array
        int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
        System.out.println("Unsorted array :" + Arrays.toString(unsorted));
        QuickSort algorithm = new QuickSort();
        // sorting integer array using quicksort algorithm
        algorithm.sort(unsorted);
        // printing sorted array
        System.out.println("Sorted array :" + Arrays.toString(unsorted));
    }
}

3- Output

Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4] 
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]

참고URL : https://stackoverflow.com/questions/8938235/sort-an-array-in-java

반응형