起泡排序和快速排序
#include "stdafx.h" #include <iostream> using namespace std; #define MAXSIZE 20 typedef struct { int r[MAXSIZE + 1]; int length; }SqList; //***********************************起泡排序*************************************begin void BubbleSort(SqList& L) { bool flag = false; for (int i = L.length; i > 1 && !flag; i--) { flag = true; for (int j = 1; j < i; j++) { if (L.r[j] > L.r[j + 1]) { flag = false; int temp = L.r[j]; L.r[j] = L.r[j + 1]; L.r[j + 1] = temp; } } } } //***********************************起泡排序*************************************end //***********************************快速排序*************************************begin int Partition(SqList& L, int low, int high) { L.r[0] = L.r[low]; while (low < high) { while(low<high && L.r[high] >= L.r[0]) { high--; } L.r[low] = L.r[high]; while(low<high && L.r[low] <= L.r[0]) { 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); } //***********************************快速排序*************************************end void SqlistPrint(SqList &L) { for (int i = 1; i <= L.length; i++) { cout<<L.r[i]<<" "; } cout<<endl; } int _tmain(int argc, _TCHAR* argv[]) { int arr[8] = {49, 38, 65, 97, 76, 13, 27, 49}; SqList QuickList; SqList BubbleList; QuickList.length = sizeof(arr)/sizeof(arr[0]); BubbleList.length = sizeof(arr)/sizeof(arr[0]); for (int i = 0; i < sizeof(arr)/sizeof(arr[0]); i++) { QuickList.r[i + 1] = arr[i]; BubbleList.r[i + 1] = arr[i]; } cout<<"*************************起泡排序**************************"<<endl; cout<<"before: "; SqlistPrint(BubbleList); BubbleSort(BubbleList); cout<<"after: "; SqlistPrint(BubbleList); cout<<"*************************快速排序**************************"<<endl; cout<<"before: "; SqlistPrint(QuickList); QuickSort(QuickList); cout<<"after: "; SqlistPrint(QuickList); cout<<endl; return 0; }
运行界面如下: