Академический Документы
Профессиональный Документы
Культура Документы
c
#include <stdio.h>
#include <stdlib.h>
#
void swap(int *a, int *b);
void quickSort( int[], int, int);
int partition( int*, int, int);
int main(int argc, char *argv[])
{
int a[] = {2, 6, 5, 1};
int i;
// int arrlength = sizeof(a); WRONG
int arrlength = 4;
printf("\n\nUnsorted array is: ");
for(i = 0; i < arrlength; ++i)
printf(" %d ", a[i]);
//array, 0, length
quickSort( a, 0, arrlength);
printf("\n\nSorted array is: ");
for(i = 0; i < arrlength; ++i)
printf(" %d ", a[i]);
printf("\n\n");
}
// char yo[] = "Hello";
// &yo[0] = will be equivalent to = Hello &yo[0] points to variable yo[0]
//array, Leftmost position, Rightmost position
void quickSort( int a[], int L, int R)
{
int k;
if( R <= L){
return;
}
k = partition( a, L, R);
quickSort( a, L, k); // Sort left half of partitioned array
quickSort( a, k+1, R); // Sort right half of partitioned array
}
, 6 , 5 , 1]
|
| once the two pointers cross we exist the while loop
.
// |
// S
|
B=4 & p[B]=1
int pivot;
int help;
int S;
int B;
S = L; //S = current Leftmost position
B = R-1;//B = rightmost position
pivot = a[R-1];
//rightmost number in array
int *pop;
pop = &a[B]; //pop points to address of array
//*pop is the actual variable in the address a[B]
while(B > S) {//as long as the two pointers don't cross you continue
if(a[B-1] > pivot){ //move to the right of the pivot
pop = &a[B-1];
B--;
}
else {
swap(&a[B-1], &a[S]);// move to left of the pivot
S++;
}
}
pop = &pivot; // Put pivot in the "hole"
return B; //return the position of the pivot
}
void swap(int *a, int *b){
int temp;
temp = *a;
*a = *b;
*b = temp;
}
// Unsorted array is:
// Sorted array is:
//
//
//
//
//
//
//
2 6 5 1
2 6 5 1
First partition:
pivot = 1;
2,6,5,5
2,6,6,5
2,2,6,5
escape while loop
1,2,6,5
'
In case anyone wants to see my Java program, this is it: ' import java.util.Arra
ys;
public class AltSorts {
public static void QuickSort( double[] a, int L, int R ){
int k;
if ( R <= L){
return;
}
k = partition( a, L, R );
// Quick sort
" + Arrays.toString(x) );