You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.5KB

  1. //
  2. // Created by red on 01/12/19.
  3. //
  4. #include "sorts.h"
  5. #include <stdio.h>
  6. #include <stddef.h>
  7. unsigned long partition(double* arr, unsigned long n) {
  8. double pivot = arr[n-1];
  9. unsigned long i = 0;
  10. for (unsigned long j = 0; j < n-1; j++) {
  11. if (arr[j] < pivot) {
  12. double tmp = arr[i];
  13. arr[i] = arr[j];
  14. arr[j] = tmp;
  15. i++;
  16. }
  17. }
  18. double tmp = arr[i];
  19. arr[i] = arr[n-1];
  20. arr[n-1] = tmp;
  21. return i;
  22. }
  23. //quicksort the array pointed at by arr, containing n elements in total.
  24. void quicksort(double* arr, unsigned long n) {
  25. if (n < 2) { return; }
  26. unsigned long pivot = partition(arr, n);
  27. quicksort(arr, pivot);
  28. quicksort(arr+pivot+1, n-pivot-1);
  29. }
  30. //Ciura (2001), A102549
  31. static size_t const gaps[8] = {701, 301, 132, 57, 23, 10, 4, 1};
  32. static size_t const gaps_num = 8;
  33. void shellsort(double* arr, size_t n) {
  34. //literally the example code from wikipedia i'm lazy
  35. for (size_t i = 0; i < gaps_num; i++){
  36. size_t gap = gaps[i];
  37. for (size_t j = gap; j < n; j++) {
  38. double tmp = arr[j];
  39. size_t k;
  40. for (k = j; k >= gap && arr[k - gap] > tmp; k -= gap) {
  41. arr[k] = arr[k-gap];
  42. }
  43. arr[k] = tmp;
  44. }
  45. }
  46. };
  47. void selectionsort(double* arr, size_t n) {
  48. for (size_t i = 0; i < n; i++) {
  49. size_t min = i;
  50. for (size_t j = i+1; j < n; j++) {
  51. if (arr[j] < arr[min]) {min = j;}
  52. }
  53. if (min != i) {
  54. double tmp = arr[i];
  55. arr[i] = arr[min];
  56. arr[min] = tmp;
  57. }
  58. }
  59. }