Java 实现 Quicksort 和 Selection
QuickSort
import java. util. Arrays;
import java. util. Random;
public class Quicksort {
private static int partition ( int [ ] arr, int low, int high) {
Random rand = new Random ( ) ;
int pivot_i = rand. nextInt ( ( high- low) ) + low;
int pivot = arr[ pivot_i] ;
arr[ pivot_i] = arr[ high] ;
arr[ high] = pivot;
int i = low - 1 ;
for ( int j = low; j <= ( high - 1 ) ; j++ ) {
if ( arr[ j] <= pivot) {
int tmp2 = arr[ ++ i] ;
arr[ i] = arr[ j] ;
arr[ j] = tmp2;
}
}
arr[ high] = arr[ ++ i] ;
arr[ i] = pivot;
return i;
}
public static void quicksort ( int [ ] arr, int low, int high) {
if ( low < high) {
int q = partition ( arr, low, high) ;
quicksort ( arr, low, q - 1 ) ;
quicksort ( arr, q + 1 , high) ;
}
}
public static void main ( String args[ ] ) {
int [ ] i = { 1 , 2 , 3 , 8 , 0 , 0 , 89 , 33 , 48 , 90 , - 89 , 48 } ;
quicksort ( i, 0 , i. length- 1 ) ;
System. out. println ( Arrays. toString ( i) ) ;
}
}
Selection
import java. util. Random;
public class Selection {
private static int partition ( int [ ] arr, int low, int high) {
Random rand = new Random ( ) ;
int pivot_i = rand. nextInt ( high- low) + low;
int pivot = arr[ pivot_i] ;
arr[ pivot_i] = arr[ high] ;
arr[ high] = pivot;
int i = low - 1 ;
for ( int j = low; j <= high- 1 ; j++ ) {
if ( arr[ j] <= pivot) {
int tmp = arr[ ++ i] ;
arr[ i] = arr[ j] ;
arr[ j] = tmp;
}
}
arr[ high] = arr[ ++ i] ;
arr[ i] = pivot;
return i;
}
public static int selection ( int [ ] arr, int low, int high, int i) {
if ( low == high) {
return arr[ low] ;
}
int q = partition ( arr, low, high) ;
int k = q - low + 1 ;
if ( i == k ) return arr[ q] ;
else if ( i < k) return selection ( arr, low, q- 1 , i) ;
else return selection ( arr, q+ 1 , high, i- k) ;
}
public static void main ( String args[ ] ) {
int [ ] i = { 1 , 6 , - 9023 , 234 , 345 , 898 , 234 , 565 , 4 , 2 , 3 , 0 , 7 } ;
int x = 1 ;
while ( x <= i. length) {
System. out. println ( selection ( i, 0 , i. length - 1 , x) ) ;
x++ ;
}
}
}