Sei sulla pagina 1di 2

public class QuickSort{

//Algorithm method found at


http://www.mathcs.emory.edu/~cheung/Courses/171/Syllabus/7-
Sort/Progs/QuickSort/2/QuickSort.java
public static void sort( double[] a )
{
double[] left = null, right = null;
int nleft, nright; // Length of left[] and right[
double pivot;
int i, j, k;

if ( a.length <= 1 )
{
// Array of 1 element is sorted....

return;
}

/* ========================================================
Select the "pivot"
======================================================== */
pivot = a[a.length-1]; // Use last element as pivot
// This is the default choice...

/* ========================================================
Find out how many elements are <= and > than pivot
======================================================== */
nleft = nright = 0;
for ( i = 0; i < a.length-1; i++ )
{
if ( a[i] <= pivot ){
nleft++;
}
else{
nright++;
}
}
/* =================================================
Make the left and right array of the proper size
================================================= */
left = new double[nleft];
right = new double[nright];

/* =================================================
Partition array into 2 halves:

all values <= pivot to left[ ] array


all values > pivot to right[ ] array
================================================= */
i = 0;
j = 0;
for ( k = 0; k < a.length-1; k++ ){

if ( a[k] <= pivot ){


left[i++] = a[k];
}
else {
right[j++] = a[k];
}
}
/* =================================================
Sort each half
================================================= */
sort(left); // Use Quick Sort
sort(right); // Use Quick Sort

/* =================================================
Concatenate the pieces back
================================================= */
k = 0;

for ( i = 0; i < left.length; i++ ){


a[k++] = left[i];
}

a[k++] = pivot;

for ( j = 0; j < right.length; j++ ){


a[k++] = right[j];
}
}

Potrebbero piacerti anche