Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // xcode
- // paulogp
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- #define MAX_ELEMENTS 30
- void swap_elements (int *x, int *y);
- int get_pivot (int the_min, int the_max);
- void quicksort (int the_list[], int the_min, int the_max);
- void print_list (int the_list[]);
- void swap_elements (int *the_a, int *the_b)
- {
- int the_temp;
- the_temp = *the_a;
- *the_a = *the_b;
- *the_b = the_temp;
- }
- int get_pivot (int the_min, int the_max)
- {
- // middle
- return ((the_min + the_max) / 2);
- }
- void quicksort (int the_list[], int the_min, int the_max)
- {
- int the_key, i, j, the_pivot;
- if (the_min < the_max)
- {
- the_pivot = get_pivot (the_min, the_max);
- swap_elements (&the_list[the_min], &the_list[the_pivot]);
- the_key = the_list[the_min];
- i = the_min + 1;
- j = the_max;
- while (i <= j)
- {
- while ((i <= the_max) && (the_list[i] <= the_key))
- i++;
- while ((j >= the_min) && (the_list[j] > the_key))
- j--;
- if (i < j)
- swap_elements (&the_list[i], &the_list[j]);
- }
- // swap two elements
- swap_elements (&the_list[the_min], &the_list[j]);
- // recursively sort the lesser list
- quicksort (the_list, the_min, (j - 1));
- quicksort (the_list, (j + 1), the_max);
- }
- }
- void print_list (int the_list[])
- {
- int i = 0;
- while (the_list[i] != '\0')
- {
- printf("%d\t", the_list[i]);
- i += 1;
- }
- }
- int main (int argc, const char * argv[])
- {
- int the_list[MAX_ELEMENTS];
- int i = 0;
- // seed the random sequence generated by rand()
- srand ((unsigned)time(NULL));
- // generate random numbers and fill them to the list
- for (i = 0; i < MAX_ELEMENTS; i++)
- {
- the_list[i] = (rand() % 20) + 1; // random from 1 to 20
- }
- printf("the list before sorting is:\n");
- print_list (the_list);
- // sort the list using quicksort
- quicksort (the_list, 0, MAX_ELEMENTS-1);
- // print the result
- printf ("\nthe list after sorting using quicksort algorithm:\n");
- print_list (the_list);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement