几种排序算法中,比较快速且不浪费空间的排序算法,就是快速排序。
java实现快速排序的代码:
package yushen0.sort;
/**
*
* @class_name QuickSort.java
* @package_name yushen0.sort
*/
public class QuickSort {
public static void main(String[] args) {
int[] nums = { 20, 56, 34, 28, 69, 77, 2, 5, 89, 100 };
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("排序之前:{");
for (int i : nums) {
strBuilder.append(i + ",");
}
String str = strBuilder.toString().substring(0, strBuilder.toString().length() - 1);
System.out.println(str + "}");
quickSort(nums, 0, nums.length - 1);
strBuilder.setLength(0);
strBuilder.append("排序之后:{");
for (int i : nums) {
strBuilder.append(i + ",");
}
String str2 = strBuilder.toString().substring(0, strBuilder.toString().length() - 1);
System.out.println(str2 + "}");
}
private static void quickSort(int[] nums, int left, int right) {
if (left < right) {
int i = left, j = right, x = nums[left];
while (i < j) {
// 从右往左找,第一个小于x的数
while (i < j && nums[j] >= x)
j--;
if (i < j)
nums[i++] = nums[j];
// 从左往右找,第一个大于x的数
while (i < j && nums[i] < x)
i++;
if (i < j)
nums[j--] = nums[i];
}
nums[i] = x;
quickSort(nums, 0, i - 1);
quickSort(nums, i + 1, right);
}
}
}
先把代码贴上,回头分析