public class TestSort { public static void main(String[] args) { int nums[] = { 7, 5, 3, 8, 4, 6, 1, 2 }; // bubbleSort(nums); quickSort(nums, 0, nums.length - 1); printNums(nums); } /** * 冒泡排序 */ public static void bubbleSort(int[] nums) { int temp; for (int i = 0; i < nums.length - 1; i++) { for (int j = 0; j < nums.length - 1 - i; j++) { if (nums[j] > nums[j + 1]) { temp = nums[j]; nums[j] = nums[j + 1]; nums[j + 1] = temp; } } } } /** * 快速排序 */ public static void quickSort(int[] nums, int left, int right) { if (left >= right) { return; } int i = left, j = right, x = nums[left]; while (i < j) { while (i < j) { if (nums[j] < x) { nums[i] = nums[j]; break; } j--; } if (i < j) { i++; } while (i < j) { if (nums[i] > x) { nums[j] = nums[i]; break; } i++; } if (i < j) { j--; } } nums[i] = x; quickSort(nums, left, i - 1); quickSort(nums, i + 1, right); } public static void printNums(int[] nums) { StringBuilder sb = new StringBuilder(); for (int num : nums) { sb.append(num + ", "); } System.out.println(sb.toString()); } }
冒泡排序,快速排序
猜你喜欢
转载自icegeneral.iteye.com/blog/2281633
今日推荐
周排行