哪些网站做的不好,建设部网站网站建设,桃源网站建设,网站所属权题目
快速排序是一种非常高效的算法#xff0c;从其名字可以看出这种排序算法最大的特点就是快。当表现良好时#xff0c;快速排序的速度比其他主要对手#xff08;如归并排序#xff09;快2#xff5e;3倍。
分析
快速排序的基本思想是分治法#xff0c;排序过程如下…题目
快速排序是一种非常高效的算法从其名字可以看出这种排序算法最大的特点就是快。当表现良好时快速排序的速度比其他主要对手如归并排序快23倍。
分析
快速排序的基本思想是分治法排序过程如下在输入数组中随机选取一个元素作为中间值pivot然后对数组进行分区partition使所有比中间值小的数据移到数组的左边所有比中间值大的数据移到数组的右边。接下来对中间值左右两侧的子数组用相同的步骤排序直到子数组中只有一个数字为止。
题目
public class Test {public static void main(String[] args) {int[] nums {4, 1, 5, 3, 6, 2, 7, 8};int[] result sortArray(nums);for (int item : result) {System.out.println(item);}}public static int[] sortArray(int[] nums) {quicksort(nums, 0, nums.length - 1);return nums;}public static void quicksort(int[] nums, int start, int end) {if (start end) {int pivot partition(nums, start, end);quicksort(nums, start, pivot - 1);quicksort(nums, pivot 1, end);}}public static int partition(int[] nums, int start, int end) {int random new Random().nextInt(end - start 1) start;swap(nums, random, end);int small start - 1;// 把所有遇到的小元素全部放到头部for (int i start; i end; i) {if (nums[i] nums[end]) {small;swap(nums, small, i);}}small;swap(nums, small, end);return small;}private static void swap(int[] nums, int index1, int index2) {if (index1 ! index2) {int temp nums[index1];nums[index1] nums[index2];nums[index2] temp;}}}