冒泡:
快排:
归并:
private static void BubbleSort(int[] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 1; j < a.length - i; j++) {
int temp;
if (a[j - 1] > a[j]) {
temp = a[j];
a[j] = a[j - 1];
a[j - 1] = temp;
}
}
}
}
快排:
private static void QuickSort(int[] a, int low, int high) {
if (low < high) {
int mid = partition(a, low, high);
QuickSort(a, low, mid - 1);
QuickSort(a, mid+1, high);
}
}
private static int partition(int[] a, int low, int high) {
int pivot = a[high];
int i = low - 1;
int temp;
for (int j = low; j < high; j++) {
if (a[j] < pivot) {
i++;
temp = a[j];
a[j] = a[i];
a[i] = temp;
}
}
temp = a[high];
a[high] = a[i+1];
a[i + 1] = temp;
return i+1;
}
归并:
private static void guiBingSort(int []a,int low,int high){
int mid = (low + high) / 2;
if (low < high) {
guiBingSort(a,low,mid);
guiBingSort(a,mid+1,high);
merge(a, low, high, mid);
}
}
private static void merge(int[] a, int low, int high, int mid) {
int[] b;
b = new int[high - low + 1];
int i = low;
int j = mid + 1;
int k = 0;
while (i<=mid&&j<=high)if (a[i]<a[j])
b[k++] = a[i++];
else b[k++] = a[j++];
while (i<=mid) b[k++] = a[i++];
while (j <= high) b[k++] = a[j++];
System.arraycopy(b,0,a,low,b.length);
}
选择:
private static void choseSort(int[] a) {
for (int i = 0; i <a.length ; i++) {
int temp;
for (int j = i+1; j <a.length ; j++) {
if (a[j] < a[i]) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
temp = a[i];
a[i] = a[i];
a[i] = temp;
}
}