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
| #include<stdio.h> #include<iostream> using namespace std; #define TRUE 1 #define FALSE 0 #define OK 1 #define ERROR 0 #define MAXSIZE 20 #define LT(a,b) (a<b) #define EQ(a,b) (a==b) typedef int Status; typedef int KeyType; typedef int InfoType; typedef struct { KeyType key; InfoType otherinfo; }RedType; typedef struct { RedType r[MAXSIZE + 1]; int length; }SqList; Status InitList(SqList &L) { L.length = 0; return OK; }
Status CreateList(SqList &L, int n) { int i; cout << "输入" << n << "个元素" << endl; for (i = 1; i <= n; i++) { cin >> L.r[i].key; ++L.length; } if (L.length == 0) return ERROR; return OK; }
Status DispList(SqList &L) { int i; if (L.length == 0) return ERROR; for (i = 1; i <= L.length; i++) { cout << L.r[i].key << " "; } cout << endl; return OK; }
int Partition(SqList &L, int low, int high) { L.r[0] = L.r[low]; int pivotkey = L.r[low].key; while (low < high) { while (low < high&&L.r[high].key >= pivotkey) --high; L.r[low] = L.r[high]; while (low < high&&L.r[low].key <= pivotkey) ++low; L.r[high] = L.r[low]; } L.r[low] = L.r[0]; return low; }
void QSort(SqList &L, int low, int high) { if (low < high) { int pivotloc = Partition(L, low, high); QSort(L, low, pivotloc - 1); QSort(L, pivotloc + 1, high); } } void QuickSort(SqList &L) { QSort(L, 1, L.length); } void main() { SqList L; int n; cout << "初始化顺序表,"; InitList(L); if (L.length == 0) cout << "顺序表为空!\n"; cout << "输入顺序表的元素个数:"; cin >> n; CreateList(L, n); cout << "输出" << n << "个元素的顺序表如下:" << endl; DispList(L); QuickSort(L); cout << "快速排序结果如下:" << endl; DispList(L); system("pause"); }
|