코딩테스트 풀이/JAVA
[프로그래머스/Lv.0] 특이한 정렬
무지맘
2023. 6. 30. 09:57
정수 n을 기준으로 n과 가까운 수부터 정렬하려고 한다. 이때 n으로부터의 거리가 같다면 더 큰 수를 앞에 오도록 배치한다.
1. Input, Output, Example
- numlist의 원소를 n으로부터 가까운 순서대로 정렬한 배열을 반환
2. Constraint
1) 1 ≤ n ≤ 10,000
2) 1 ≤ numlist의 원소 ≤ 10,000
3) 1 ≤ numlist의 길이 ≤ 100
4) numlist는 중복된 원소를 갖지 않는다.
3. Code
class Solution {
static int standard;
public int[] solution(int[] numlist, int n) {
standard = n;
quicksort(numlist, 0, numlist.length-1);
return numlist;
}
static void quicksort(int[] arr, int start, int end){
if(start>=end)
return;
int pivot = start;
int i = start+1, j = end, temp;
while(i<=j) {
while(i<=end && compare(arr[i],arr[pivot]))
i++;
while(j>start && compare(arr[pivot],arr[j]))
j--;
if(i>j) {
temp = arr[j];
arr[j] = arr[pivot];
arr[pivot] = temp;
} else {
temp = arr[j];
arr[j] = arr[i];
arr[i] = temp;
}
}
quicksort(arr, start, j-1);
quicksort(arr, j+1, end);
}
static boolean compare(int a, int b){ // a가 앞쪽이라면 true
int da = Math.abs(standard-a), db = Math.abs(standard-b);
if(da==db) return a>=b;
else return da<=db;
}
}
- +1