Let’s improve the bubble sort program of Homework 7 Problem 1 - use two function
ID: 3850975 • Letter: L
Question
Let’s improve the bubble sort program of Homework 7 Problem 1 - use two functions—bubbleSort and swap. Function bubbleSort sorts the array. It calls function swap to exchange the array elements array[j] and array[j + 1]. Remember that C enforces information hiding between functions, so swap does not have access to individual array elements in bubbleSort. Because bubbleSort wants swap to have access to the array elements to be swapped, bubbleSort passes each of these elements by reference to swap—the address of each array element is passed explicitly. Although entire arrays are automatically passed by reference, individual array elements are scalars and are ordinarily passed by value. Therefore, bubbleSort uses the address operator (&) on each of the array elements in the swap call to effect pass-by-reference as: swap( &array[ j ], &array[ j + 1 ] );
Function swap receives &array[j] in pointer variable say element1Ptr. Even though swap—because of information hiding—is not allowed to know the name array[j], swap may use *element1Ptr as a synonym for array[j]—when swap references *element1Ptr, it’s actually referencing array[j] in bubbleSort. Similarly, when swap references *element2Ptr, it’s actually referencing array[j + 1] in bubbleSort.
int hold = array[ j ];
array[ j ] = array[ j + 1 ];
array[ j + 1 ] = hold;
Even though swap is not allowed to say precisely the same effect is achieved by
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
Explanation / Answer
#include <stdio.h>
void swap(int *element1Ptr,int *element2Ptr) //swap two numbers using pointers
{
int hold = *element1Ptr;
*element1Ptr = *element2Ptr;
*element2Ptr = hold;
}
void bubblesort(int array[],int n )
{
int i,j;
for (i = 0 ; i < ( n - 1 ); i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (array[j] > array[j+1])
{
swap(&array[j], &array[j+1]);// passing address of array elements to swap function
}
}
}
}
int main(void)
{
int array[100], n, i;
printf("Enter number of elements ");
scanf("%d", &n);
printf("Enter %d integers ", n);
for (i = 0; i < n; i++)
scanf("%d", &array[i]);
bubblesort(array,n); //call to bubblesort function
printf("Sorted list in ascending order: ");
for ( i = 0 ; i < n ; i++ )
printf("%d ", array[i]);
return 0;
}
Output:
Enter number of elements 10
Enter 10 integers 56 78 34 -7 91 23 53 39 49 21
Sorted list in ascending order:
-7
21
23
34
39
49
53
56
78
91
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.