當前位置:編程學習大全網 - 源碼下載 - 急啊!求壹段關於java 的快速排序的代碼

急啊!求壹段關於java 的快速排序的代碼

public class quickSort {

public quickSort() {

}

public void printA(int[] a) {

for (int i = 0; i < a.length; i++) {

System.out.print(a[i] + " ");

}

System.out.println();

}

public void chooseSort(int[] a, int left, int right) {

int smallest;

int flagIndex = 0;

int forSwap;

boolean flag;

for (int i = left; i < right; i++) {

smallest = a[i];

// System.out.println("first" + smallest);

flagIndex = i;

flag = false;

for (int j = i + 1; j <= right; j++) {

if (a[j] < smallest) {

smallest = a[j];

flagIndex = j;

flag = true;

// System.out.println(smallest + " " + flagIndex);

}

}

if(flag){

forSwap = a[i];

a[i] = smallest;

a[flagIndex] = forSwap;

// System.out.println(smallest);

// printA(a);

// printA(a);

}

}

}

public void quickSort(int[] a, int left, int right) {

int index;

// printA(a);

if (left < right && right - left > 10) { //可以優化如果數組元素小於10就用選擇排序

index = partition(a, left, right);

quickSort(a, left, index - 1);

quickSort(a, index + 1, right);

} else {

chooseSort(a, left, right);

}

}

public int partition(int[] a, int left, int right) {

int result = getMiddle(a[left], a[right], a[(int) ((left + right) / 2)]);

int flagIndex;

if (result == 1) {

flagIndex = left;

} else if (result == 2) {

flagIndex = right;

} else {

flagIndex = (int) ((left + right) / 2);

}

int lowIndex, highIndex;

lowIndex = left - 1;

highIndex = right + 1;

int compareValue = a[flagIndex];

int k = a[left];

a[left] = compareValue;

a[flagIndex] = k;

// System.out.println(compareValue);

while (lowIndex + 1 != highIndex) {

if (a[lowIndex + 1] <= compareValue) {

lowIndex++;

} else if (a[highIndex - 1] >= compareValue) {

highIndex--;

} else {

k = a[lowIndex + 1];

a[++lowIndex] = a[highIndex - 1];

a[--highIndex] = k;

}

}

// printA(a);

a[left] = a[lowIndex];

a[lowIndex] = compareValue;

return lowIndex;

}

public int getMiddle(int a, int b, int c) {

if (a >= b) {

if (b >= c) {

return 2;

} else {

if (a >= c) {

return 3;

} else {

return 1;

}

}

} else {

if (c >= b) {

return 2;

} else {

if (a >= c) {

return 1;

} else {

return 3;

}

}

}

// return 0;

}

}

  • 上一篇:用這六個AI神器就夠了。
  • 下一篇:關於1998年微軟的重大反壟斷案件
  • copyright 2024編程學習大全網