快速排序
package jh;
public class QuickSort {
public static int partition(int[] array,int start,int end){
int base = array[start];
while (start < end){
// 注意此处是有等号的,也就是说等于的时候不做移动(这点很重要,不然有可能会会陷入死循环!!!!!!!!!)
while (start < end && array[end]>=base){
end--;
}
array[start] = array[end];
while (start <end && array[start]<=base){
start++;
}
array[end] = array[start];
}
array[end] = base;
return start;
}
public static int partition2(int[] array,int start,int end){
int base = array[start];
while (start < end){
// 注意此处是有等号的,也就是说等于的时候不做移动(这点很重要,不然有可能会会陷入死循环!!!!!!!!!)
while (start < end && array[end]>=base){
end--;
}
swap(array,start,end);
while (start <end && array[start]<=base){
start++;
}
swap(array,start,end);
}
// array[end] = base;
return start;
}
public static void quickSort(int[] array,int start,int end){
if (start < end){
int index = partition(array,start,end);
quickSort(array,start,index-1);
quickSort(array,index+1,end);
}
}
public static void swap(int[] arr,int i,int j){
int temp = arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public static void main(String[] args) {
int[] array = {2,4,6,1,3,5,23,98,13};
quickSort(array,0,array.length-1);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
}
冒泡排序
public static void bubleSort(int[] nums){
for (int i = 1; i < nums.length; i++) {
for (int j = 0; j < nums.length-i; j++) {
if (nums[j+1]<nums[j]){
swap(nums,j,j+1);
}
}
}
}
选择排序
public static void selectSort(int[] nums){
for (int i = 0; i < nums.length - 1; i++) {
int minIndex = i;
int min = nums[i];
for (int j = i+1; j < nums.length; j++) {
if(nums[j]<nums[i]){
min = nums[j];
minIndex=j;
}
}
swap(nums,i,minIndex);
}
}
标签:end,nums,int,length,start,算法,array,排序
From: https://www.cnblogs.com/chenyi502/p/17847823.html