快速排序
第一种
class Solution {
public int partition(int s, int e, int[] nums){
int key = nums[s];
int i = s, j = e;
while(true){
while(i < j && nums[j] >= key) j--;
while(i < j && nums[i] <= key) i++;
if(i < j){
int tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}else {
nums[s] = nums[i];
nums[i] = key;
break;
}
}
return i;
}
public void QuickSort(int s, int e, int[] nums){
if(s > e) return;
int part = partition(s, e, nums);
QuickSort(s, part-1,nums);
QuickSort(part+1, e, nums);
}
public void sortColors(int[] nums) {
int n = nums.length;
QuickSort(0, n-1, nums);
}
}
第二种
class Solution {
public int partition(int s, int e, int[] nums){
int pivot = nums[s];
int low = s, high = e;
while(low < high){
while(low < high && nums[high] >= pivot) high--;
nums[low] = nums[high];
while(low < high && nums[low] <= pivot) low++;
nums[high] = nums[low];
}
nums[low] = pivot;
return low;
}
public void QuickSort(int s, int e, int[] nums){
if(s > e) return;
int part = partition(s, e, nums);
QuickSort(s, part-1,nums);
QuickSort(part+1, e, nums);
}
public void sortColors(int[] nums) {
int n = nums.length;
QuickSort(0, n-1, nums);
}
}
冒泡排序
class Solution {
public void sortColors(int[] nums) {
int n = nums.length;
for(int i = 1; i < n; i++){
for(int j = 0; j < n-i; j++){
if(nums[j] > nums[j+1]){
int tmp = nums[j];
nums[j] = nums[j+1];
nums[j+1] = tmp;
}
}
}
}
}