Advertisement
dmilicev

bubble_sort_array_of_integers_without_pointers_v1.c

May 19th, 2020
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.07 KB | None | 0 0
  1. /*
  2.  
  3.     bubble_sort_array_of_integers_without_pointers_v1.c
  4.  
  5. To solve this task, we must use pointers, at least implicitly, covertly.
  6.  
  7. In order for the sort function to change the given array,
  8. we must give the function the address of the first member of the array
  9. (this is pointer) and an integer n number of array members.
  10.  
  11. So, we still use pointers.
  12.  
  13. The pointer is arr and it is the address of the first element of the array.
  14. Based on integer n, the function knows that starting from address arr
  15. there are n integers next to each other.
  16.  
  17. arr = & arr [0]
  18.  
  19. The addresses of the other elements (integers) are
  20.  
  21. arr + 1 = &arr[1]
  22. arr + 2 = &arr[2]
  23. ...
  24. arr + i = &arr[i], (i goes from 0 to n-1)
  25. ...
  26. arr + n-1 = &arr[n-1]
  27.  
  28. n is the ordinal number of the array element (going from 1 to n),
  29.  
  30. and i is the index of the array element (going from 0 to n-1).
  31.  
  32.  
  33.     You can find all my C programs at Dragan Milicev's pastebin:
  34.  
  35.     https://pastebin.com/u/dmilicev
  36.  
  37. */
  38.  
  39. #include <stdio.h>
  40.  
  41.  
  42. // Function to print array, n is number of elements in array arr[]
  43. // text[] describes the shown array arr[]
  44. void ShowArray(char text[],int arr[],int n)
  45. {
  46.     int i;
  47.  
  48.     printf("%s",text);
  49.     for(i=0;i<n;i++)
  50.         printf("%5d", arr[i]);
  51.  
  52.     printf("\n");
  53. }
  54.  
  55.  
  56. // function bubbleSort to sort the array in ascending order
  57. void bubbleSort(int arr[], int n)
  58. {
  59.     int i, j, temp;
  60.  
  61.     for (i = 0; i < n-1; i++)
  62.         for (j = 0; j < n-i-1; j++)     // Last i elements are already in place
  63.             if (arr[j] > arr[j+1])      // arr[j] < arr[j+1] for descending order
  64.             {
  65.                 temp = arr[j];
  66.                 arr[j] = arr[j+1];
  67.                 arr[j+1] = temp;
  68.             }
  69. }
  70.  
  71.  
  72. // Main program to test above function
  73. int main(void)
  74. {
  75.     int arr[10]={5,2,-7,8,-3,1,9,3,7,1};    // array of 10 integers
  76.     int n = sizeof(arr)/sizeof(arr[0]); // a way to get n, number of elements in array arr[]
  77.     int i;
  78.  
  79.     printf("\n Array arr[] has n = %d integers. \n", n);
  80.  
  81.     ShowArray("\n Unsorted array of integers is: \n\n",arr,n);
  82.  
  83.     bubbleSort(arr,n);
  84.  
  85.     ShowArray("\n Array sorted by bubble sort is: \n\n",arr,n);
  86.  
  87.  
  88.     return 0;
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement