fork download
  1. #include <stdio.h>
  2.  
  3. /* prints array */
  4. void pa (int *a, int len, char *s);
  5. int comp=0,swaps=0;
  6. int main() {
  7. /* unsorted array */
  8. int a[] = {10,2,3,4,5,6,7,8,9,1};
  9. int a_len = sizeof(a)/sizeof(int);
  10. pa(a, a_len, "unsorted array");
  11.  
  12. /* sort array */
  13. int issorted = 1;
  14. do {
  15. printf("\tsorting..\n");
  16. issorted = 1;
  17. int c;
  18. for (c = 1; c <a_len ; c++) {
  19. comp++;
  20. if (a[c] < a[c-1]) {
  21. swaps++;
  22. issorted = 0;
  23. // printf("\t\tswapping a[%d]=%d and a[%d]=%d\n", c-1, a[c-1], c, a[c]);
  24. int tmp = a[c];
  25. a[c] = a[c-1];
  26. a[c-1] = tmp;
  27. }
  28. }
  29. } while (issorted == 0);
  30. printf("comparisons = %d swaps=%d\n",comp,swaps);
  31. pa(a, a_len, "sorted array");
  32.  
  33. return 0;
  34. }
  35.  
  36. /* prints array */
  37. void pa (int *a, int len, char *s) {
  38. printf("%s: ", s);
  39. int c;
  40. for (c = 0; c < len; c++) {
  41. printf("%d ", a[c]);
  42. }
  43. printf("\n");
  44. }
  45.  
Success #stdin #stdout 0s 2292KB
stdin
Standard input is empty
stdout
unsorted array: 10 2 3 4 5 6 7 8 9 1 
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
	sorting..
comparisons = 90  swaps=17
sorted array: 1 2 3 4 5 6 7 8 9 10