1. 快速排序
public class quick_sort
{
public int partition(int[]nums, int begin, int end){
int val = nums[begin];
int low = begin;
int high = end;
while(low < high){
while(low < high && nums[high] < val){
high --;
}
while(low < high && nums[low] >= val){
low ++;
}
swap(nums, low, high);
}
swap(nums, begin, low);
return low;
}
public void swap(int[]A, int x, int y){
if(x == y) return;
A[x] = A[x] ^ A[y];
A[y] = A[x] ^ A[y];
A[x] = A[x] ^ A[y];
//int tem = A[x];
//A[x] = A[y];
//A[y] = tem;
}
public void sort(int[]nums, int begin, int end){
if(begin >= end) return;
int index = partition(nums, begin, end);
sort(nums, begin, index-1);
sort(nums,index + 1, end);
}
public static void main(String[] args)
{
int[] a={2,1,3,6,8,7};
quick_sort helper = new quick_sort();
helper.sort(a,0,a.length - 1);
for(int num : a){
System.out.println(num);
}
}
}
2.归并排序
public class merge_sort
{
public static void merge(int[]nums, int begin, int mid, int end){
int[] tmp = new int[end - begin + 1];
int i =begin;
int j = mid + 1;
int k =0;
while(i <= mid && j <=end){
if(nums[i] <= nums[j]){
tmp[k++] = nums[i++];
}else{
tmp[k++] = nums[j++];
}
}
while(i <= mid) tmp[k++] = nums[i++];
while(j <= end) tmp[k++] = nums[j++];
for(int p = 0; p < tmp.length; p++){
nums[p+begin] = tmp[p];
}
}
public static void sort(int[] nums, int begin, int end){
if(begin >= end) return;
int mid = (begin + end) >>> 1;
sort(nums, begin, mid);
sort(nums, mid + 1, end);
merge(nums, begin, mid, end);
}
public static void main(String[] args)
{
int[] nums = {8,4,6,3,1,7,2,5,6};
sort(nums,0,nums.length - 1);
for(int num : nums){
System.out.println(num);
}
}
}
3. 堆排序
import java.util.Arrays;
public class heap_sort
{
public static void downAdjust(int[]nums, int parentIndex, int length){
int tmp = nums[parentIndex];
int childIndex = parentIndex * 2 + 1;
while(childIndex < length ){
int anotherChildIndex = childIndex + 1;
if(anotherChildIndex < length && nums[anotherChildIndex] > nums[childIndex]){
childIndex = anotherChildIndex;
}
if(tmp >= nums[childIndex]){
break;
}
nums[parentIndex] = nums[childIndex];
parentIndex = childIndex;
childIndex = childIndex * 2 +1;
}
nums[parentIndex] = tmp;
}
public static void main(String[] args)
{
int[]nums={3,5,2,1,4,7,6,8};
int len = nums.length;
for(int i = (len - 2)/2; i >= 0; i-- ){
downAdjust(nums, i, len);
}
System.out.println(Arrays.toString(nums));
for(int i= len - 1; i > 0; i--){
int tmp = nums[i];
nums[i] = nums[0];
nums[0] = tmp;
downAdjust(nums, 0, i);
}
System.out.println(Arrays.toString(nums));
}
}