快排
public class QuickSort {
public static int [ ] Sort ( int [ ] a, int left, int right) {
if ( left< right) {
int mid= position ( a, left, right) ;
a= Sort ( a, left, mid- 1 ) ;
a= Sort ( a, mid+ 1 , right) ;
}
return a;
}
public static int position ( int a[ ] , int left, int right) {
int pivot= a[ left] ;
int i= left+ 1 ;
int j= right;
while ( true ) {
while ( i<= j&& a[ i] <= pivot) i++ ;
while ( i<= j&& a[ j] >= pivot) j-- ;
if ( i>= j)
break ;
int temp= a[ i] ;
a[ i] = a[ j] ;
a[ j] = temp;
}
a[ left] = a[ j] ;
a[ j] = pivot;
return j;
}
public static void main ( String[ ] args) {
int a[ ] = new int [ ] { 5 , 7 , 6 , 4 , 2 , 1 } ;
Sort ( a, 0 , 5 ) ;
for ( int i= 0 ; i< a. length; i++ ) {
System. out. print ( a[ i] + " " ) ;
}
}
}
堆排序
public class sorttt {
public static void heapify ( int tree[ ] , int n, int i) {
if ( i>= n) {
return ;
}
int c1= 2 * i+ 1 ;
int c2= 2 * i+ 2 ;
int max= i;
if ( c1< n&& tree[ c1] > tree[ max] ) {
max= c1;
}
if ( c2< n&& tree[ c2] > tree[ max] ) {
max= c2;
}
if ( max!= i) {
swap ( tree, max, i) ;
heapify ( tree, n, max) ;
}
}
public static void swap ( int a[ ] , int i, int j) {
int temp= a[ i] ;
a[ i] = a[ j] ;
a[ j] = temp;
}
public static void build_heap ( int tree[ ] , int n) {
int lastnode= n- 1 ;
int parentnode= ( lastnode- 1 ) / 2 ;
for ( int i = parentnode; i >= 0 ; i-- ) {
heapify ( tree, n, i) ;
}
}
public static void heap_sort ( int tree[ ] , int n) {
build_heap ( tree, n) ;
for ( int i = n- 1 ; i >= 0 ; i-- ) {
swap ( tree, i, 0 ) ;
heapify ( tree, i, 0 ) ;
}
}
public static void main ( String[ ] args) {
int tree[ ] = new int [ ] { 4 , 10 , 3 , 5 , 1 , 2 } ;
int n= 6 ;
heap_sort ( tree, n) ;
for ( int i = 0 ; i < n; i++ ) {
System. out. print ( tree[ i] + " " ) ;
}
}
}