1 #include<iostream> 2 using namespace std; 3 4 void quick(int a[],int left, int right) 5 { 6 if (left == right) 7 return; 8 int index = (right + left + 1) / 2; 9 int temp; 10 temp = a[index]; 11 a[index] = a[right]; 12 a[right] = temp; 13 int p = 0; 14 int prev = -1; 15 while (p != right) 16 { 17 if (a[p] >= a[right]) 18 { 19 if ((p - prev) != 1) 20 { 21 prev++; 22 temp = a[p]; 23 a[p] = a[prev]; 24 a[prev] = temp; 25 } 26 else 27 prev++; 28 } 29 p++; 30 } 31 prev++; 32 temp = a[p]; 33 a[p] = a[prev]; 34 a[prev] = temp; 35 if(prev!=left) 36 quick(a, left, prev-1); 37 if(prev!=right) 38 quick(a, prev+1, right); 39 } 40 41 int main() 42 { 43 int n,temp; 44 cout << "請輸入數組個數:" << endl; 45 cin >> n; 46 int *a = new int [n]; 47 for (int i = 0; i < n; i++) 48 { 49 cin >> temp; 50 a[i] = temp; 51 } 52 53 //冒泡排序-從小到大 54 for(int i=0;i<n-1;i++) 55 for(int j=0;j<n-1-i;j++) 56 if (a[j] > a[j + 1]) 57 { 58 temp = a[j]; 59 a[j] = a[j + 1]; 60 a[j + 1] = temp; 61 } 62 for (int i = 0; i < n; i++) 63 cout << a[i]; 64 cout << endl; 65 66 //選擇排序-從大到小 67 int i,j,max; 68 for (i = 0; i < n - 1; i++) 69 { 70 max = i; 71 for (j = i; j < n; j++) 72 if (a[j] > a[max]) 73 max = j; 74 if (max != i) 75 { 76 temp = a[i]; 77 a[i] = a[max]; 78 a[max] = temp; 79 } 80 } 81 for (int i = 0; i < n; i++) 82 cout << a[i]; 83 cout << endl; 84 85 //插入排序-從小到大 86 for (i = 1; i < n; i++) 87 { 88 temp = a[i]; 89 j = i - 1; 90 while (j >= 0 && a[j] > temp) 91 { 92 a[j + 1] = a[j]; 93 j--; 94 } 95 a[j + 1] = temp; 96 } 97 for (int i = 0; i < n; i++) 98 cout << a[i]; 99 cout << endl; 100 101 //快速排序-從大到小 102 quick(a,0, n - 1); 103 for (int i = 0; i < n; i++) 104 cout << a[i]; 105 cout << endl; 106 107 delete[] a; 108 system("pause"); 109 return 0; 110 111 }