# How to count number of swaps in a bubble sort?

user4766244

So I need my program to print the values entered and count the number of swaps(not comparisons). So far I have everything working except the swap counter. I tried just incrementing by using `swap++;` in my if statement along with the bubble sort but that doesn't work. Any ideas? Here is my code.

``````#include <stdio.h>

int sort(int array[], int count);

int main(void) {

int numArray[100];
int counter, value;

printf("Enter array length \n");
scanf("%d", &counter);

int i = 0;
while(i < counter){
scanf("%d", &numArray[i]);
i++;
}

i = 0;
while(i < counter) {
sort(numArray, counter);
i++;
}

int totalSwaps = sort(numArray, counter);
printf("Swaps: %d\n", totalSwaps);

i = 0;
while(i < counter) {
printf("Values: %d\n", numArray[i]);
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;
}
``````
ProfOak

You have a while loop to sort it `count` number of times. You only need to run your sort function once, unless it doesn't sort the first time.

``````#include <stdio.h>

int sort(int array[], int count);

int main(void){

int numArray[100];
int counter;

printf("Enter array length \n");
scanf("%d", &counter);

int i;
for (i = 0; i < counter; i++){
printf("%d. Enter a numner: ", i);
scanf("%d", &numArray[i]);
}

// How many times would you like to sort this array?
// You only need one sort
/*
i = 0;
while(i < counter){
sort(numArray, counter);
i++;
}
*/

int totalSwaps = sort(numArray, counter);

if (totalSwaps == 0) {
printf("The array is already in sorted order\n");
return 0;
}

printf("Swaps: %d\n", totalSwaps);

for (i = 0; i < counter; i++) {
printf("Values: %d\n", 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;
}
``````

Collected from the Internet

edited at