You are viewing a single comment's thread. Return to all comments →
void countSwaps(int n, int a[]) { int numSwaps = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; numSwaps++; } } } printf("Array is sorted in %d swaps.\n", numSwaps); printf("First Element: %d\n", a[0]); printf("Last Element: %d\n", a[n - 1]); } int main() { int n; scanf("%d", &n); int a[n]; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } countSwaps(n, a); return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
Sorting: Bubble Sort
You are viewing a single comment's thread. Return to all comments →
include
void countSwaps(int n, int a[]) { int numSwaps = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n - 1; j++) { if (a[j] > a[j + 1]) { int temp = a[j]; a[j] = a[j + 1]; a[j + 1] = temp; numSwaps++; } } } printf("Array is sorted in %d swaps.\n", numSwaps); printf("First Element: %d\n", a[0]); printf("Last Element: %d\n", a[n - 1]); } int main() { int n; scanf("%d", &n); int a[n]; for (int i = 0; i < n; i++) { scanf("%d", &a[i]); } countSwaps(n, a); return 0; }