1.冒泡排序
public static void bubbleSort(int[] nums){
for(int i = 0; i < nums.length - 1; i++){
boolean flag = true;
for(int j = 0; j < nums.length - 1 - i; j++){
if(nums[j] > nums[j + 1]){
int temp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = temp;
flag = false;
}
}
if(flag == true)
break;
}
}
2.快速排序
public static int getMiddle(int[] nums, int low, int high) {
int pivot = nums[low];
while(low < high){
while(low < high && nums[high] >= temp){
high--;
}
nums[low] = nums[high];
while(low < high && nums[low] < temp){
low++;
}
nums[high] = nums[low];
}
nums[low] = pivot;
return low;
}
public static void quickSort(int[] nums, int low, int high){
if(low < high){
int middle = getMiddle(nums, low, high);
quickSort(nums, low, middle - 1);
quickSort(nums, middle + 1, high);
}
}
3.选择排序
public static void selectionSort(int[] nums){
for(int i = 0; i < nums.length - 1; i++){
int min = i;
for(int j = i; j < nums.length; j++){
if(nums[j] < nums[min]){
min = j;
}
}
int temp = nums[min];
nums[min] = nums[i];
nums[i] = temp;
}
}
4.插入排序
public static void insertionSort(int[] nums){
for(int i = 0; i < nums.length; i++){
int temp = nums[i];
int j;
for(j = i; j > 0 && temp < nums[j - 1]; j--){
nums[j] = nums[j - 1];
}
nums[j] = temp;
}
}
5.归并排序
public static void mergeSort(int[] nums){
sort(nums, 0, nums.length - 1, new int[nums.length]);
}
public static void sort(int[] nums, int low, int high, int[] tempArr){
if(low >= high){
return;
}
int mid = low + (high - low) / 2;
sort(nums, low, mid, tempArr);
sort(nums, mid + 1, high, tempArr);
merge(nums, low, high, mid, tempArr);
}
public static void merge(int[] nums, int low, int high, int mid, int[] tempArr){
int left = low;
int right = mid + 1;
int index = low;
while(left <= mid && right <= high){
if(nums[left] <= nums[right]) {
tempArr[index++] = nums[left++];
}else{
tempArr[index++] = nums[right++];
}
}
while(right <= high){
tempArr[index++] = nums[right++];
}
while(left <= mid){
tempArr[index++] = nums[left++];
}
for(index = low; index <= high; index++){
nums[index] = tempArr[index];
}
}