=
快速排序与归并排序
1.快速排序
代码如下(示例):
package Sort.Quicksort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] array = {
-9, 78, 0, 23, -567, 70};
int[] array1 = {
-7,-5,-9,2,1};
quicksort(array1,0, array1.length-1);
System.out.println(Arrays.toString(array1));
}
public static void quicksort(int[] array, int left, int right) {
int l = left;
int r = right;
int pivot = array[(left + right) / 2];
int temp = 0;
while (l < r) {
while (array[l] < pivot) {
l = l + 1;
}
while (array[r] > pivot) {
r = r - 1;
}
if (l >= r) {
break;
}
temp = array[r];
array[r] = array[l];
array[l] = temp;
if (array[l]==pivot){
r= r-1;
}
if (array[r]==pivot){
l=l+1;
}
}
if (l==r){
l = l+1;
r = r-1;
}
if (left<r){
quicksort(array,left,r);
}
if (right>l){
quicksort(array,l,right);
}
}
}
2.归并排序
代码如下(示例):
package Sort.MergeSort;
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] array = {
9, 8, 7, 6, 5, 4, 3, 2, 1};
int[] temp = new int[array.length];
mergesort(array,0, array.length-1,temp);
System.out.println(Arrays.toString(array));
}
public static void mergesort(int[] array, int left, int right, int temp[]) {
if (left < right) {
int mid = (left + right) / 2;
mergesort(array, left, mid, temp);
mergesort(array, mid + 1, right, temp);
merge(array,left,mid,right,temp);
}
}
/**
* @param array 给定的数组
* @param left 给定数组的起始索引
* @param mid 给定数组的中间索引
* @param right 给定数组的最后索引
* @param temp 临时数组,用来得到最后的目标数组
*/
public static void merge(int[] array, int left, int mid, int right, int[] temp) {
int i = left;
int j = mid + 1;
int t = 0;
while (i <= mid && j <= right) {
if (array[i] <= array[j]) {
temp[t] = array[i];
i++;
t++;
} else {
temp[t] = array[j];
j++;
t++;
}
}
while (i <= mid) {
temp[t] = array[i];
i++;
t++;
}
while (j <= right) {
temp[t] = array[j];
j++;
t++;
}
t = 0;
int templsft = left;
while (templsft <= right) {
array[templsft] = temp[t];
templsft++;
t++;
}
}
}
总结
都用到递归的方法。认真理解下!