Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- bubble_sort_array_of_integers_without_pointers_v1.c
- To solve this task, we must use pointers, at least implicitly, covertly.
- In order for the sort function to change the given array,
- we must give the function the address of the first member of the array
- (this is pointer) and an integer n number of array members.
- So, we still use pointers.
- The pointer is arr and it is the address of the first element of the array.
- Based on integer n, the function knows that starting from address arr
- there are n integers next to each other.
- arr = & arr [0]
- The addresses of the other elements (integers) are
- arr + 1 = &arr[1]
- arr + 2 = &arr[2]
- ...
- arr + i = &arr[i], (i goes from 0 to n-1)
- ...
- arr + n-1 = &arr[n-1]
- n is the ordinal number of the array element (going from 1 to n),
- and i is the index of the array element (going from 0 to n-1).
- You can find all my C programs at Dragan Milicev's pastebin:
- https://pastebin.com/u/dmilicev
- */
- #include <stdio.h>
- // Function to print array, n is number of elements in array arr[]
- // text[] describes the shown array arr[]
- void ShowArray(char text[],int arr[],int n)
- {
- int i;
- printf("%s",text);
- for(i=0;i<n;i++)
- printf("%5d", arr[i]);
- printf("\n");
- }
- // function bubbleSort to sort the array in ascending order
- void bubbleSort(int arr[], int n)
- {
- int i, j, temp;
- for (i = 0; i < n-1; i++)
- for (j = 0; j < n-i-1; j++) // Last i elements are already in place
- if (arr[j] > arr[j+1]) // arr[j] < arr[j+1] for descending order
- {
- temp = arr[j];
- arr[j] = arr[j+1];
- arr[j+1] = temp;
- }
- }
- // Main program to test above function
- int main(void)
- {
- int arr[10]={5,2,-7,8,-3,1,9,3,7,1}; // array of 10 integers
- int n = sizeof(arr)/sizeof(arr[0]); // a way to get n, number of elements in array arr[]
- int i;
- printf("\n Array arr[] has n = %d integers. \n", n);
- ShowArray("\n Unsorted array of integers is: \n\n",arr,n);
- bubbleSort(arr,n);
- ShowArray("\n Array sorted by bubble sort is: \n\n",arr,n);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement