class Quick{
public void swap(int[] arr,int i,int j) { //数值的交换
int temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
public int[] Sort(int[] arr,int low,int high) { //进行快速排序
int pivot;//记录下标
if(low<high) {
pivot=partition(arr,low,high); //记录轴下标
Sort(arr,low,pivot-1); //左边的序列进行快速排序
Sort(arr,pivot+1,high); //右边的序列进行快速排序
}
return arr;
}
public int partition(int[] arr,int low,int high) {
int pivotValue=arr[low]; //第一个元素作为轴值
while(low<high) {
while(low<high&&arr[high]>=pivotValue)
high--;
swap(arr,low,high);//若从末尾数起,存在小于轴值的数则交换数值
while(low<high&&arr[low]<=pivotValue)
low++;
swap(arr,low,high);//若头部数起,存在大于轴值的数则交换数值
}
return low;
}
}
public class QuickSort {
public static void main(String[] args) {
int[] arr= {10,50,40,60,80,70,90,20,30};
int[] temp=new int[arr.length];
int length=arr.length-1;
Quick quickSort=new Quick();
temp=quickSort.Sort(arr, 0, length);
System.out.println("快速排序后的数组序列为:");
for(int i=0;i<arr.length;i++) {
System.out.print(temp[i]+" ");
}
}
}
Python实现快速排序
def swap(items,i,j): #交换数值
temp=items[i]
items[i]=items[j]
items[j]=temp
def Multiply_Sort(items,low,high): #进行快速排序
pivotValue=items[low]
while low<high:
if low<high and items[high]>=pivotValue:
high=high-1
swap(items,low,high)
if low<high and items[low]<=pivotValue:
low=low+1
swap(items,low,high)
return low
def QuickSort(items,low,high):
if low<high:
pivot=Multiply_Sort(items,low,high)
QuickSort(items,low,pivot-1)
QuickSort(items,pivot+1,high)
return items
if __name__=="__main__":
arr=[10,50,40,30,20,70,60,80,90]
result=QuickSort(arr,0,8)
print(result)