一、冒泡排序
public static void 冒泡(int[] nums){
boolean b = true;
for (int i = 0,n = nums.length; i < n && b; i++) {
b = false;
for (int j = 0; j < n - i - 1; j++) {
if (nums[j] < nums[j+1]){
int temp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = temp;
b = true;
}
}
}
System.out.println(Arrays.toString(nums));
}
二、选择排序
public static void 选择(int[] nums){
for (int i = 0,n = nums.length; i < n - 1; i++) {
int maxIndex = i;
for (int j = i; j < n; j++) {
if (nums[j] > nums[maxIndex]){
maxIndex = j;
}
}
int temp = nums[i];
nums[i] = nums[maxIndex];
nums[maxIndex] = temp;
}
System.out.println(Arrays.toString(nums));
}
三、插入排序
public static void 插入(int[] nums){
for (int i = 1,前一个元素值下标,n = nums.length; i < n; i++) {
int 当前元素值 = nums[i];
for (前一个元素值下标 = i - 1; 前一个元素值下标 >= 0 && nums[前一个元素值下标] > 当前元素值; 前一个元素值下标--) {
nums[前一个元素值下标+1] = nums[前一个元素值下标];
}
nums[前一个元素值下标 + 1] = 当前元素值;
}
System.out.println(Arrays.toString(nums));
}
四、快速排序
private static void quickSort(int[] nums) {
quickSort(nums, 0, nums.length - 1);
}
private static void quickSort(int[] nums, int low, int high) {
if (low >= high) { return; }
int[] p = partition(nums, low, high);
System.out.println("===============>" + Arrays.toString(p));
quickSort(nums, low, p[0] - 1);
quickSort(nums, p[0] + 1, high);
}
private static int[] partition(int[] nums, int low, int high) {
int less = low - 1, more = high;
System.out.println("less:" + less + ",more:" + more);
System.out.println(Arrays.toString(nums));
System.out.println(">>>>>>>>>>>>>>>>");
while (low < more) {
if (nums[low] < nums[high]) {
swap(nums, ++less, low++);
System.out.println(Arrays.toString(nums));
} else if (nums[low] > nums[high]) {
swap(nums, --more, low);
System.out.println(Arrays.toString(nums));
} else {
++low;
}
}
System.out.println("<<<<<<<<<<<<<<<<");
System.out.println(Arrays.toString(nums));
System.out.println("more:" + more + ",high:" + high);
swap(nums,more,high);
System.out.println(Arrays.toString(nums));
System.out.println("return:" + (less + 1) + "," + more);
return new int[] {less + 1, more};
}
|