【编程题】快速排序(java实现)
通过荷兰国旗问题得出快排
package niuke;
import java.util.Arrays;
public class HeLanGuoQi {
public static void main(String[] args){
int[] arr={4,5,6,7,5,1,2,3};
rotate(arr,5);
System.out.println(Arrays.toString(arr));
}
static void rotate(int[] arr,int num){
if(arr==null||arr.length<=0)return;
int left=-1,right=arr.length,current=0;
while (current<right){
if(arr[current]<num){
left++;
swap(arr,left,current);
current++;
}
else if(arr[current]==num){
current++;
}else {
right--;
swap(arr,current,right);
}
}
}
static void swap(int[] arr,int i,int j){
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
package sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args){
int[] arr={4,5,6,7,5,1,2,3};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
static void quickSort(int[] arr,int low,int high){
if(low>=high)return;
int[] nums=partition(arr,low,high);
quickSort(arr,low,nums[0]-1);
quickSort(arr,nums[1]+1,high);
}
static int[] partition(int[] arr,int low,int high){
if(arr==null||arr.length<=0)return null;
int left=low-1,right=high+1,current=low,num=arr[high];
while (current<right){
if(arr[current]<num){
left++;
swap(arr,left,current);
current++;
}
else if(arr[current]==num){
current++;
}else {
right--;
swap(arr,current,right);
}
}
return new int[] {left+1,right-1};
}
static void swap(int[] arr,int i,int j){
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
随机快排
package sort;
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args){
int[] arr={4,5,6,7,5,1,2,3};
quickSort(arr,0,arr.length-1);
System.out.println(Arrays.toString(arr));
}
static void quickSort(int[] arr,int low,int high){
if(low>=high)return;
swap(arr,low+(int)Math.random()*(high-low+1),high);//随机快排
int[] nums=partition(arr,low,high);
quickSort(arr,low,nums[0]-1);
quickSort(arr,nums[1]+1,high);
}
static int[] partition(int[] arr,int low,int high){
if(arr==null||arr.length<=0)return null;
int left=low-1,right=high+1,current=low,num=arr[high];
while (current<right){
if(arr[current]<num){
left++;
swap(arr,left,current);
current++;
}
else if(arr[current]==num){
current++;
}else {
right--;
swap(arr,current,right);
}
}
return new int[] {left+1,right-1};
}
static void swap(int[] arr,int i,int j){
int temp=arr[j];
arr[j]=arr[i];
arr[i]=temp;
}
}
本文深入探讨了Java中快速排序算法的实现,包括荷兰国旗问题的解决策略,标准快速排序及随机化快速排序的代码实现。通过对不同场景的分析,展示了快速排序在数据处理中的高效性和灵活性。
712

被折叠的 条评论
为什么被折叠?



