Advertisement
Guest User

Uppgift5wrkimg

a guest
Sep 19th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.28 KB | None | 0 0
  1. /* Program has 1 function swaps() that puts negative elements in the
  2. leftmost indices, and positive elements in the rightmost indices.
  3. It does not necessarily order the elements by size however.
  4. It uses two pointers that start by pointing to the beginning
  5. and end of the array. When the two pointers meet, the swapping is done.*/
  6.  
  7. #include <stdio.h>
  8. #include <stdlib.h>
  9. #define N 8 // some arbitrary array length just for testing
  10.  
  11. // Takes an array as parameter, modifies its elements, and returns the modified array
  12. int* swaps(int* array);
  13.  
  14. void main(){
  15.  
  16. // Create and initialize an int array
  17. int i;
  18. int *array = malloc(sizeof(int)*N);
  19. // remember to add spacebar between input integers
  20. for(i = 0; i < N; i++){
  21. scanf("%d", &array[i]);
  22. }
  23.  
  24. // Print before swapping
  25. for(i = 0; i < N; i++){
  26. printf("[");
  27. printf("%d", array[i]);
  28. if(i == N-1){
  29. printf("] ");
  30. } else {
  31. printf("],");
  32. }
  33. }
  34. printf("\n");
  35. // Call swaps with argument being the newly created array of length N
  36. swaps(array);
  37.  
  38. // Print after swapping
  39. for(i = 0; i < N; i++){
  40. printf("[");
  41. printf("%d", array[i]);
  42. if(i == N-1){
  43. printf("] ");
  44. } else {
  45. printf("],");
  46. }
  47. }
  48. printf("\n");
  49. }
  50.  
  51. // Time complexity is O(n^2), however this problem should be able to solve in O(n)
  52. int* swaps(int* array){
  53.  
  54. int* ptr1;
  55. ptr1 = &array[0];
  56. int* ptr2;
  57. ptr2 = &array[N-1];
  58. int tmp;
  59.  
  60.  
  61. for(ptr1; ptr1 <= &array[N-1]; ptr1++){
  62. if(ptr1==ptr2){
  63. return array;
  64. }
  65. if(*ptr1 >= 0){
  66. for(ptr2; ptr2 >= &array[0]; ptr2--){
  67. if(ptr1==ptr2){
  68. return array; // have to check ptr2==ptr1 all the time, otherwise ptr2 will keep iterating
  69. }
  70.  
  71. // swap elements that ptr1 and ptr2 point to
  72. if(*ptr2 < 0){
  73. tmp = *ptr2;
  74. *ptr2 = *ptr1;
  75. *ptr1 = tmp;
  76. ptr2--;
  77. if(ptr1==ptr2){
  78. return array; // have to check ptr2==ptr1 after ptr 2 decr, otherwise ptr2 will keep iterating
  79. }
  80. break;
  81. }
  82. }
  83. }
  84. }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement