标签:
冒泡:
package Sort; public class BubbleSort { public static void main(String[] args) { int[] list = new int[]{12,14,3,24,1,33}; int[] nums = bubbleSort(list); for(int i = 0;i< list.length;i++){ System.out.println(nums[i]); } } public static int[] bubbleSort(int[] nums){ int n = nums.length; for(int i= 0;i<n;i++){ for(int j= i+1;j<n-i-1;j++){ int temp = nums[i]; nums[i] = nums[j]; nums[j] = temp; } } return nums; } }
快排:
package Sort; public class QuickSort { public static void main(String[] args) { int[] unsortedList = new int[] { 49, 38, 65, 97, 76, 13, 27, 49 }; quickSort(unsortedList, 0, 7); for (int i = 0; i < unsortedList.length; i++) { System.out.println(unsortedList[i]); } } public static void quickSort(int[] unsortedList, int low, int high) { if (low < high) {// 只有一个元素时,退出 int k = partition(unsortedList, low, high); quickSort(unsortedList, low, k - 1); quickSort(unsortedList, k + 1, high); } } /** * nums进行一次以pivot为界限的分割 * * @param nums * @param low * @param high * @return */ public static int partition(int[] nums, int low, int high) { // 定义pivot,存储pivot,定义low high if (low == high) return low; int pivot = nums[low]; // low==high时,停止本趟partition while (low < high) { // 定义low,high,从high开始寻找比pivot小的数,放进坑里 while (low < high && nums[high] >= pivot) high--; nums[low] = nums[high]; // 从low开始寻找比pivot大的数,放进坑里 while (low < high && nums[low] <= pivot) low++; nums[high] = nums[low]; } nums[low] = pivot; return low; } }
标签:
原文地址:http://www.cnblogs.com/jinxialiu/p/5862909.html