Prelude to Programming 6th Edition Chapter 8 Short Answer qu
Prelude to Programming (6th Edition) Chapter 8 Short Answer question 16.
 How many interchanges take place when sorting the following numbers in descending order, using the bubble sort technique? 6958
Solution
#include <stdio.h>
int sort(int array[], int count);
int main(void){
int numArray[4]={6,9,5,8};
 int counter=4;
 int totalSwaps = sort(numArray, counter);
if (totalSwaps == 0) {
 printf(\"The array is already in sorted order\ \");
 return 0;
 }
printf(\"Swaps: %d\ \", totalSwaps);
 int i;
 for (i = 0; i < counter; i++) {
 printf(\"%d\\t\", numArray[i]);
 }
 return 0;
 }
int sort(int array[], int count){
int i, j, temp;
 int swaps = 0;
 for(i = 0; i < count-1; ++i){
for(j=0; j<count-1-i; ++j){
if(array[j] < array[j+1]){
temp = array[j+1];
 array[j+1] = array[j];
 array[j] = temp;
 swaps++;
 }
 }
 }
return swaps;
 }
========================================
Output:
akshay@akshay-Inspiron-3537:~/Chegg$ gcc bubble.c
 akshay@akshay-Inspiron-3537:~/Chegg$ ./a.out
 Swaps: 3
 9   8   6   5  
==================================================
Hence total 3 swaps will take place.
In first pass of 6 9 5 8
9 6 5 8
9 6 8 5
In second pass 9 8 6 5
Hence total 3 swaps will take place


