퀵 정렬은 배열에서 하나의 요소를 선택하여 기준(pivot)으로 삼는다. 그리고 배열의 왼쪽 부분과 오른쪽 부분에서 인덱스 값을 탐색하며 기준보다 크거나 작으면 그 두 수를 서로 교환하는 방식이다.
▼퀵 정렬 코드
import java.io.*;
import java.util.*;
public class Main {
public static void Swap(int arr[], int idx1, int idx2)
{
int temp = arr[idx1];
arr[idx1]=arr[idx2];
arr[idx2]=temp;
}
public static void QuickSort(int arr[], int left, int right)
{
if(left<=right)
{
int pivot = Partition(arr,left,right);
QuickSort(arr,left,pivot-1);
QuickSort(arr,pivot+1,right);
}
}
public static int Partition(int arr[], int left, int right)
{
int pivot = arr[left];
int low = left+1;
int high = right;
while(low<=high)
{
while( low<=right && pivot>=arr[low])
low++;
while( high>=(left+1) && pivot<=arr[high])
high--;
if(low<=high)
Swap(arr,low,high);
}
Swap(arr,left,high);
return high;
}
public static void main(String[] args){
int arr[] = {5,3,8,4,9,1,6,2,7};
System.out.print("정렬 전 배열 : ");
for(int val : arr)
System.out.print(val+" ");
QuickSort(arr,0,8);
System.out.println();
System.out.print("정렬 후 배열 : ");
for(int val : arr)
System.out.print(val+" ");
}
}
결과
정렬 전 배열 : 5 3 8 4 9 1 6 2 7
정렬 후 배열 : 1 2 3 4 5 6 7 8 9
'CS > 자료구조' 카테고리의 다른 글
자료구조 - 이진탐색트리 (0) | 2024.01.31 |
---|---|
자료구조 - 보간 탐색 (0) | 2024.01.26 |
자료구조 - 병합정렬 (0) | 2024.01.24 |
자료구조 - 힙 정렬 (0) | 2024.01.23 |
자료 구조 - 버블, 선택, 삽입 정렬의 시간복잡도 (0) | 2024.01.23 |