1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
| #include <stdio.h> #include <stdlib.h> int cnt=0; void selectSort(int a[], int n){ int i, j, d, temp, count=0; for(i=0;i<n-1;i++){ d=i; for(j=i+1;j<n;j++){ count++; if(a[j]<a[d]) d=j; } if(d!=i){ temp=a[d]; a[d]=a[i]; a[i]=temp; } } for(i=0;i<n-1;i++) printf("%d ", a[i]); printf("%d\n", a[i]); printf("%d\n", count); } void bubbleSort(int a[], int n){ int i, j, temp, flag=1, count=0; for(i=n-1;i>0&&flag==1;i--){ flag=0; for(j=0;j<i;j++){ count++; if(a[j]>a[j+1]){ temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; flag=1; } } } for(i=0;i<n-1;i++) printf("%d ", a[i]); printf("%d\n", a[i]); printf("%d\n", count); } void adjust(int a[], int i, int n){ int j, temp; temp=a[i]; j=2*i+1; while(j<n){ cnt++; if(j<n-1&&a[j]<a[j+1]) j++; if(temp>=a[j]) break; a[(j-1)/2]=a[j]; j=2*j+1; } a[(j-1)/2]=temp; } void heapSort(int a[], int n){ int i, temp; for(i=n/2-1;i>=0;i--) adjust(a,i,n); for(i=n-1;i>=1;i--){ temp=a[i]; a[i]=a[0]; a[0]=temp; adjust(a,0,i); } for(i=0;i<n-1;i++) printf("%d ", a[i]); printf("%d\n", a[i]); printf("%d\n", cnt); } void merge(int a[], int tmp[], int left, int leftend, int rightend){ int i=left, j=leftend+1, q=left; while(i<=leftend&&j<=rightend){ cnt++; if(a[i]<=a[j]) tmp[q++]=a[i++]; else tmp[q++]=a[j++]; } while(i<=leftend) tmp[q++]=a[i++]; while(j<=rightend) tmp[q++]=a[j++]; for(i=left;i<=rightend;i++) a[i]=tmp[i]; } void mSort(int a[], int temp[], int left, int right){ int center; if(left<right){ center = (left+right)/2; mSort(a,temp,left,center); mSort(a,temp,center+1,right); merge(a,temp,left,center,right); } } void mergeSort(int a[], int n){ int *temp; int i; temp=(int*)malloc(n*sizeof(int)); mSort(a,temp,0,n-1); free(temp); for(i=0;i<n-1;i++) printf("%d ", a[i]); printf("%d\n", a[i]); printf("%d\n", cnt); } void swap(int a[], int i, int j){ int temp; temp=a[i]; a[i]=a[j]; a[j]=temp; } void sort(int a[], int left, int right){ int i, last; if(left<right){ last=left; for(i=left+1;i<=right;i++){ cnt++; if(a[i]<a[left]) swap(a,++last,i); } swap(a,left,last); sort(a,left,last-1); sort(a,last+1,right); } } void quickSort(int a[], int n){ int i; sort(a,0,n-1); for(i=0;i<n-1;i++) printf("%d ", a[i]); printf("%d\n", a[i]); printf("%d\n", cnt); } int main(){ int a[102]={0}, n, op, i; scanf("%d %d", &n, &op); for(i=0;i<n;i++) scanf("%d", &a[i]); switch(op){ case 1: selectSort(a,n); break; case 2: bubbleSort(a,n); break; case 3: heapSort(a,n); break; case 4: mergeSort(a,n); break; case 5: quickSort(a,n); break; } return 0; }
|