[Java] 藍橋杯ALGO-59 演算法訓練 快速排序
問題描述
快速排序是最經常使用的一種排序方式,對於給定的n個數組成的一個數組,請使用快速排序對其進行排序。
輸入格式
第一行一個數N。
輸出格式
共N行,每行一個數,表示所求序列。
樣例輸入
5
1
4
2
3
樣例輸出
1
2
3
4
資料規模和約定
共10組資料。
對100%的資料,N<=10^5,所有數均為非負數且在int範圍內。
package algo59; // 自己寫的快速排序在遇到一個極端情況,會出現超時 import java.io.*; import java.util.Arrays; public class Main { public static void main(String[] args) throws IOException { BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); int n = Integer.parseInt(reader.readLine()); num = new int[n]; for (int i = 0; i < n; i++) { num[i] = Integer.parseInt(reader.readLine()); } reader.close(); // quickSort(); Arrays.sort(num); for (int i = 0; i < num.length; i++) { System.out.println(num[i]); } } private static int[] num; // private static void quickSort() { // quickSort(0, num.length - 1); // } // // private static void quickSort(int l, int r) { // if (l < r) { // int pivot = partion(l, r); // quickSort(l, pivot - 1); // quickSort(pivot + 1, r); // } // } // // private static int partion(int l, int r) { // swap(l, (l + r) / 2); // int pivot = l; // while (true) { // while (l <= r && num[l] < num[pivot]) { // l++; // } // while (l <= r && num[r] > num[pivot]) { // r--; // } // // if (l < r) { // swap(l, r); // l++; // r--; // } else { // break; // } // } // swap(r, pivot); // return r; // } // // private static void swap(int i, int j) { // int temp = num[i]; // num[i] = num[j]; // num[j] = temp; // } }ofollow,noindex" target="_blank">❤❤點選這裡 -> 訂閱PAT、藍橋杯、GPLT天梯賽、LeetCode題解離線版❤❤
