快速排序
1、关键函数(分割左右部分的函数)
//进行数据基数位置确认函数,并对序列进行划分为两个左右序列
private static int parter(int[] arr, int low, int high) {
// TODO Auto-generated method stub
int temp = arr[low];//第一个元素为枢纽
while(low<high){
//右边查找
while(low<high && arr[high] >= temp){
high--;
}
arr[low] = arr[high];//将其进行赋值
//左边查找
while(low<high && arr[low] <= temp){
low++;
}
arr[high] = arr[low];
}
arr[low] = temp;
return low;
}
2、递归进行排序函数
//快速排序
static void QuickSort(int[] arr,int low,int high){
if(low < high){
int pos = parter(arr,low,high);
QuickSort(arr,low,pos-1);//左边子表进行快速排序
QuickSort(arr, pos+1, high);//右边子表进行快速排序
}
}
3、主函数
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {45,23,12,34,24,1,2,4,6};
//BubbleSort(arr);
QuickSort(arr,0,8);
for(int i = 0;i<arr.length;i++){
System.out.print(" "+arr[i]);
}
}
测试运行截图: