On the March-附快速排序和堆排序代码
Posted 爱犬小灰灰
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了On the March-附快速排序和堆排序代码相关的知识,希望对你有一定的参考价值。
import java.util.*;
/**
quickSort
input:3 2 4 5 1
output:[1, 2, 3, 4, 5]
*/
public class quickSort0330{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] s = str.trim().split(" ");
int n = s.length;
int[] arr = new int[n];
for(int i = 0;i < n;i++){
arr[i] = Integer.parseInt(s[i]);
}
quickSort(arr,0,n - 1);
System.out.println(Arrays.toString(arr));
}
private static void quickSort(int[] arr,int lo,int hi){
if(lo >= hi) return;
int pivot = partition(arr,lo,hi);
quickSort(arr,lo,pivot - 1);
quickSort(arr,pivot + 1,hi);
}
private static int partition(int[] arr,int lo,int hi){
Random random = new Random();
int pivotIndex = random.nextInt(hi - lo + 1) + lo;
int pivotValue = arr[pivotIndex];
swap(arr,pivotIndex,hi);
int savedPosition = hi;
hi--;
while(lo <= hi){
if(arr[lo] > pivotValue){
swap(arr,lo,hi);
hi--;
}else{
lo++;
}
}
swap(arr,lo,savedPosition);
return lo;
}
private static void swap(int[] arr,int i,int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
import java.util.*;
/*
3 2 4 1 5
[1, 2, 3, 4, 5]
*/
public class heapSort0330{
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String str = scanner.nextLine();
String[] s = str.trim().split(" ");
int n = s.length;
int[] arr = new int[n];
for(int i = 0;i < n;i++){
arr[i] = Integer.parseInt(s[i]);
}
heapSort(arr);
System.out.println(Arrays.toString(arr));
}
private static void heapSort(int[] arr){
int n = arr.length;
for(int i = n / 2 - 1;i >= 0;i--){
adjustHeap(arr,i,n);
}
for(int j = n - 1;j > 0;j--){
swap(arr,0,j);
adjustHeap(arr,0,j);
}
}
private static void adjustHeap(int[] arr,int i,int n){
int tmp = arr[i];
for(int k = i * 2 + 1;k < n;k = k * 2 + 1){
if(k + 1 < n && arr[k] < arr[k + 1]){
k++;
}
if(arr[k] > tmp){
swap(arr,i,k);
i = k;
} else{
break;
}
}
}
private static void swap(int[] arr,int i,int j){
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
以上是关于On the March-附快速排序和堆排序代码的主要内容,如果未能解决你的问题,请参考以下文章