백준 24091번 알고리즘 수업-퀵 정렬2-JAVA

sujin·2025년 3월 24일

코딩테스트-백준

목록 보기
16/18

📝문제

📝알고리즘

//의사 코드에 따라 퀵 정렬을 작성함..!

📝구현

import java.io.*;
import java.util.*;

public class Main{
    static int K, count=0;
    static int[] A;
    public static void main(String[] args)throws IOException{
        BufferedReader rd=new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st=new StringTokenizer(rd.readLine());
        int N=Integer.parseInt(st.nextToken());
        K=Integer.parseInt(st.nextToken());
        A=new int[N];
        st=new StringTokenizer(rd.readLine());
        for(int i=0; i<N; i++){
            A[i]=Integer.parseInt(st.nextToken());
        }
        quick_sort(0, N-1);
       
        System.out.print("-1");
    }
    
    static void quick_sort(int p, int r){
        if(p<r){
            int q=partition(p,r);
            quick_sort(p,q-1);
            quick_sort(q+1, r);
        }
    }
    static int partition(int p, int r){
        int x=A[r];
        int i=p-1;
        
        for(int j=p; j<r;j++){
            if(A[j]<=x){
                swap(++i, j);
            }
        }
        if(i+1!=r){
            swap(i+1, r);
        }
        return i+1;
    }
    static void swap(int i, int j){
        if(i!=j){
            int temp=A[i];
            A[i]=A[j];
            A[j]=temp;
        }
        count++;
         if(count==K){
            for(int num:A){
                System.out.print(num+" ");
            }
            System.exit(0);
        }
    }
}
profile
열공!

0개의 댓글