快速排序是对冒泡排序的一种改进,平均时间复杂度是O(nlogn)
import java.util.Arrays; import java.util.Scanner; public class test02{ public static void main(String[] args) { int n = 1; while (n != 0){ Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); int s[] = new int[n]; for (int i = 0; i < n; i++) { s[i] = scanner.nextInt(); } sort(s, 0, n - 1); System.out.println(Arrays.toString(s)); } } public static void sort(int[] s, int low, int high){ int left = low; int right = high; int temp; if(low<high){ while(left<right){ while(left<high&&s[left]<=s[low]){ left++; } while(right>low&&s[right]>s[low]){ right--; } if(left<right){ temp = s[left]; s[left] = s[right]; s[right] = temp; } } temp = s[low]; s[low] = s[right]; s[right] = temp; sort(s, low, right-1); sort(s, right+1, high); } } }
排序算法----快速排序java
时间: 2024-12-29 16:27:48