归并排序:
public void sort(int[] nums,int left,int right,int[] temp){
if(left < right){
int mid = left + (right - left) / 2;//开始递归划分
sort(nums,left,mid,temp);//归并排序左部分(left,mid)
sort(nums,mid+1,right,temp);//归并排序右部分(mid+1,right)
merge(nums,left,mid,right,temp);//合并
}
}
private void merge(int[] nums, int left, int mid, int right, int[] temp) {
int i = left; // 左部分首元素
int j = mid + 1; // 右部分首元素
int t = 0;
while(i <=mid && j <=right){//在范围之内
if(nums[i] <= nums[j]){
temp[t++] = nums[i++];
}else{
temp[t++] = nums[j++];
}
}
while (i <= mid){//右边遍历完事了 左边还剩呢
temp[t++] = nums[i++];
}
while(j <= right){//左边遍历完事了 右边还剩了
temp[t++] = nums[j++];
}
t = 0;//将temp中的元素 全部都copy到原数组里边去
while (left <=right){
nums[left++] = temp[t++];
}
}
快速排序:
public void QKSort(int a[], int low, int high){
if(low < high){
int pos = QKPass(a, low, high);
QKSort(a, low, pos-1);
QKSort(a, pos+1, high);
}
}
public int QKPass(int a[], int low, int high){
int x = a[low];
while (low < high){
while(low < high && a[high] >= x){
high--;
}
if(low < high){
a[low] = a[high];
low++;
}
while(low < high && a[low] <= x){
low++;
}
if(low < high){
a[high] = a[low];
high--;
}
}
a[low] = x;
return low;
}
选择排序:
public static int[] ChoiceSort(int[] a){
if(a == null || a.length <= 0){
return null;
}
for (int i = 0; i < a.length-1; i++) {
int min = i;
for(int j = i;j < a.length;j++){
if(a[min] > a[j])
min = j;
}
if(i != min){
int temp = a[min];
a[min] = a[i];
a[i] = temp;
}
}
return a;
}
冒泡排序:
//冒泡排序
for(int i = 0; i < arr.length - 1; i++){
for(int j = 0; j < arr.length - 1 - i; j++){
if(arr[j] > arr[j + 1]){
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}