126k views
1 vote
Using a bubble sort on the array below, write a c program that counts how many swaps occur in each pass of the array.

97, 16, 45, 63, 13, 22, 7, 58, 72

Output would look like:
Pass #1: 8
Pass #2: 4
Pass #3: 3
Pass #4: 2
Pass #5: 1
Pass #6: 1
Pass #7: 0
Pass #8: 0

1 Answer

3 votes

Final answer:

A C program was written to implement bubble sort on a given array and it counts the number of swaps in each pass. The provided code includes a swap function and the main logic to print the number of swaps for each pass of the bubble sort algorithm.

Step-by-step explanation:

The student has asked for a C program that implements the bubble sort algorithm on an array and counts the number of swaps that occur in each pass. The output is supposed to list the number of swaps for each pass. Let's write such a program, assuming we have a function called swap() that swaps two elements:

#include

void swap(int *xp, int *yp) {
int temp = *xp;
*xp = *yp;
*yp = temp;
}

int main() {
int arr[] = {97, 16, 45, 63, 13, 22, 7, 58, 72};
int n = sizeof(arr)/sizeof(arr[0]);
int i, j, swapCount;

for (i = 0; i < n-1; i++) {
swapCount = 0;
for (j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(&arr[j], &arr[j+1]);
swapCount++;
}
}
printf("Pass #%d: %d\\", i+1, swapCount);
if (swapCount == 0)
break;
}
return 0;
}

This program performs a bubble sort on the given array, and on each pass, it prints out the number of swaps that were made. The output matches the student's expected result if the array is sorted within first few passes, further passes show zero swaps owing to the sorted nature of the array.

User Cyupa
by
8.7k points