package com.mfl;
public class TestKuaiPai {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = { 13, 81, 92, 43, 65, 31, 57, 26, 75, 0 };
KuaiPai.quicksort(a, 0, a.length - 1);
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
}
class KuaiPai {
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
/**
* 此方法将三元素中的最小者被分在a[left] 三元素中的最大者被分在a[right] 枢纽元放在a[right-1]
*
* @param a
* @param left
* @param right
* @return
*/
public static int median(int[] a, int left, int right) {
int center = (left + right) / 2;
if (a[center] < a[left]) {
swap(a, left, center);
}
if (a[right] < a[left]) {
swap(a, left, right);
}
if (a[right] < a[center]) {
swap(a, right, center);
}
swap(a, center, right - 1);
return a[right - 1];
}
public static void quicksort(int[] a, int left, int right) {
if (a.length == 0)
return;
if (a.length == 1)
return;
int pivot = median(a, left, right);
int i = left + 1;
int j = right - 2;
if (j > left && i < right) {
for (;;) {
while (a[i] < pivot) {
i++;
}
while (a[j] > pivot) {
j--;
}
if (i < j) {
swap(a, i, j);
} else
break;
}
swap(a, i, right - 1);
quicksort(a, left, i - 1);
quicksort(a, i + 1, right);
} else {
median(a, left, right);
}
}
}
请问应该怎样限制条件防止数组越界呢?谢谢
------最佳解决方案--------------------------------------------------------
如果数据只剩下2个呢?你还找什么Center??
如果数据就剩下1个呢?你还left ,right?
所以,如果right-left的差距小于3,你要单独处理。
------其他解决方案--------------------------------------------------------
好吧,我承认,我看不下去了,冒昧的问一句,楼主想要什么样的排序方法。
快速排序?代码如下:
package src;
class quicksort
{
public int data[];
private int partition(int sortArray[],int low,int hight)
{
int key = sortArray[low];
while(low<hight)
{
while(low<hight && sortArray[hight]>=key)
hight--;
sortArray[low] = sortArray[hight];
while(low<hight && sortArray[low]<=key)
low++;
sortArray[hight] = sortArray[low];
}
sortArray[low] = key;
return low;
}
public void sort(int low,int hight)