Advertisement
Guest User

Untitled

a guest
Oct 23rd, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4.  
  5. #define LIM_LOW 10
  6. #define LIM_HIGH 2000
  7.  
  8. #define REVERSE_POS 0
  9. #define SORTED_POS 1
  10.  
  11. void bound(int* x, int l, int h) {
  12. if(*x > h)
  13. *x = h;
  14. if(*x < l)
  15. *x = l;
  16. }
  17.  
  18. int** cut(int* arr, int N, int k) {
  19. int** res = (int **) malloc(sizeof(int *) * 2);
  20. res[REVERSE_POS] = (int *) malloc(sizeof(int) * (N - k));
  21. res[SORTED_POS] = (int *) malloc(sizeof(int) * k);
  22. // copy sorted
  23. for(int i = 0; i < k; ++i)
  24. res[SORTED_POS][i] = arr[i];
  25. // reverse copy
  26. for(int i = 0; i < N - k; ++i) // if even we have overlap, so prevent it
  27. res[REVERSE_POS][i] = arr[N - i - 1];
  28. return res;
  29. }
  30.  
  31. void dostuff(int* arr, int N) {
  32. int lower = 2, higher = N - 2;
  33. bound(&lower, 2, N);
  34. bound(&higher, 1, N - 2);
  35. int k = (rand() % (higher - lower) + lower);
  36. printf("Cutting at %d\n", k);
  37. int** partitioned = cut(arr, N, k);
  38.  
  39. // edit our array
  40. for(int i = 0; i < N - k; ++i)
  41. arr[i] = partitioned[REVERSE_POS][i];
  42. for(int i = 0; i <= k; ++i)
  43. arr[N - k + i] = partitioned[SORTED_POS][i];
  44. for(int i = 0; i < 2; ++i)
  45. free(partitioned[i]);
  46. free(partitioned);
  47. }
  48.  
  49. void show_arr(int* arr, int N) {
  50. for(int i = 0; i < N; ++i)
  51. printf("%d ", arr[i]);
  52. }
  53.  
  54. void find_elem(int* arr, int N, int rank) {
  55. // find negative difference position
  56. int low, high;
  57. for(low = N - 2, high = N - 1; high < N && arr[high] - arr[low] >= 0; --low, --high);
  58. // high holds the beginning of sorted area, low holds end of reverse area
  59. printf("%d %d\n", low, high);
  60. int count = 0, temp = rank, pos = high;
  61. while(temp) {
  62. if(high < N)
  63. pos = high++;
  64. else if(low >= 0)
  65. pos = low--;
  66. ++count;
  67. --temp;
  68. }
  69. printf("Element on rank %d is: %d", rank, arr[pos]);
  70. }
  71.  
  72. int main() {
  73. srand(time(0));
  74. /*int N, *arr;
  75. printf("How many elements [%d .. %d]: ", LIM_LOW, LIM_HIGH);
  76. scanf("%d", &N);
  77. printf("%d Enter array elements...\n", N);
  78. bound(&N, LIM_LOW, LIM_HIGH);
  79. arr = (int *) malloc(sizeof(int) * N);
  80. for(int i = 0; i < N; ++i) {
  81. printf("a_%d: ", i);
  82. scanf("%d", &arr[i]);
  83. }*/
  84. int N = 12;
  85. int arr[] = { 2, 13, 22, 32, 41, 56, 77, 81, 99, 101, 232, 534 };
  86. dostuff(arr, N);
  87. show_arr(arr, N);
  88. int r;
  89. printf("\nEnter rank: ");
  90. scanf("%d", &r);
  91. bound(&r, 1, N);
  92. find_elem(arr, N, r);
  93. free(arr);
  94. return 0;
  95. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement