Advertisement
Guest User

Untitled

a guest
Nov 12th, 2019
71
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. //method to calculate the sum
  5. int sum(int* arr, int n) {
  6. // your code for sum
  7. int a = 0;
  8. for(int i = 0; i < n; i++)
  9. {
  10. a += arr[i];
  11. }
  12. return a;
  13. }
  14.  
  15. int partitionFunc(int arr[], int left, int right){
  16. int pivot = arr[right];
  17. int partition = (left-1);
  18. for(int j = left; j <= right-1; j++)
  19. {
  20. if(arr[j] < pivot){
  21. partition++;
  22. int temp = arr[j];
  23. arr[j] = arr[partition];
  24. arr[partition] = temp;
  25. }
  26. }
  27. int t = arr[partition+1];
  28. arr[partition+1] = arr[right];
  29. arr[right] = t;
  30.  
  31. return partition+1;
  32. }
  33.  
  34. void quickSort(int* arr, int left, int right){
  35. if(left < right){
  36. int partition = partitionFunc(arr,left,right);
  37. quickSort(arr, left, partition-1);
  38. quickSort(arr, partition+1, right);
  39. }
  40. }
  41. int main(){
  42.  
  43. int n;
  44. printf("Enter a positive integer: ");
  45. scanf("%d", &n);
  46.  
  47. for(int i = 2; i < n; i++){
  48. bool is_prime = true;
  49. for(int j = 2; j <i; j++){
  50. if(i%j == 0){
  51. is_prime = false;
  52. }
  53. }
  54. if(is_prime){
  55. printf("%d \n", i);
  56. }
  57. }
  58.  
  59. //task 3
  60.  
  61. printf("\nTask 3 Arrays \n");
  62. int m;
  63. printf("Input Size of Array: ");
  64. scanf("%d", &m);
  65. int arr[m];
  66.  
  67. for(int i = 0; i < m; i++){
  68. int t;
  69. printf("Input an integer: ");
  70. scanf("%d", &t);
  71. arr[i] = t;
  72. }
  73.  
  74. int s = sum(arr, m);
  75. printf("Number of numbers: %d \n", m);
  76. for(int j = 0; j < m; j++){
  77. printf("Input %d: %i \n", (j+1), arr[j]);
  78. }
  79. printf("The sum is: %d", s);
  80.  
  81.  
  82. //task 4
  83. printf("\n");
  84. printf("\nQuick Sort\n");
  85. int x;
  86. printf("Input Size of Array: ");
  87. scanf("%d", &x);
  88. int arr2[x];
  89.  
  90. for(int z = 0; z < x; z++){
  91. int y;
  92. printf("Input an integer: ");
  93. scanf("%d", &y);
  94. arr2[z] = y;
  95. }
  96.  
  97. quickSort(arr2, 0, (x-1));
  98. printf("Sorted Array: \n");
  99. for(int j = 0; j < x; j++){
  100. printf("%d, ", arr2[j]);
  101. }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement