天天看點

java中位數_JAVA中位數排序

package quickSort;

public class QuickSort {

private static int count;

public static void main(String[] args) {

int[] num = {3,45,78,64,52,11,64,55,99,11,18};

System.out.println(arrayToString(num,"未排序"));

QuickSort(num,0,num.length-1);

System.out.println(arrayToString(num,"排序"));

System.out.println("數組個數:"+num.length);

System.out.println("循環次數:"+count);

}

private static void QuickSort(int[] num, int left, int right) {

//如果left等于right,即數組隻有一個元素,直接傳回

if(left>=right) {

return;

}

//設定最左邊的元素為基準值

int key=num[left];

//數組中比key小的放在左邊,比key大的放在右邊,key值下标為i

int i=left;

int j=right;

while(i

//j向左移,直到遇到比key小的值

while(num[j]>=key && i

j--;

}

//i向右移,直到遇到比key大的值

while(num[i]<=key && i

i++;

}

//i和j指向的元素交換

if(i

int temp=num[i];

num[i]=num[j];

num[j]=temp;

}

}

num[left]=num[i];

num[i]=key;

count++;

QuickSort(num,left,i-1);

QuickSort(num,i+1,right);

}

private static String arrayToString(int[] arr,String flag) {

String str = "數組為("+flag+"):";

for(int a : arr) {

str += a + "\t";

}

return str;

}