1.冒泡排序:
int A[] = { 1,2,3,4,5,7,8,9,90,543,345,678,890,123,432,543,654,765,867 }; void swap(int& a,int& b) { ?? ?int tmp; ?? ?tmp = a; ?? ?a = b; ?? ?b = tmp; }
void sortpaopao(int a[],int length) { ?? ?int loop; ?? ?for (loop = 0; loop < length - 1; loop++) { ?? ??? ?for (int i = 0; i < length - loop - 1; i++) { ?? ??? ??? ?if (a[i]>a[i+1]) { ?? ??? ??? ??? ?int tmp = a[i]; ?? ??? ??? ??? ?a[i] = a[i+1]; ?? ??? ??? ??? ?a[i + 1] = tmp; ?? ??? ??? ?} ?? ??? ?} ?? ?} }
2.选择排序(不稳定)
void selectionSort(int a[], int length) { ?? ?for (int loop = 1; loop < length; loop++) { ?? ??? ?for (int j = 0; j < length - loop; j++) { ?? ??? ??? ?if (a[j] > a[length-loop]) {//把每一次循环中最大的那个放在最后面 ?? ??? ??? ??? ?swap(a[j], a[length - loop]); ?? ??? ??? ?} ?? ??? ?} ?? ?} }
3.推排序(不稳定)
void heapify(int b[],int loopSize,int i) { ?? ?int top = i; ?? ?int lson = 2 * i + 1; ?? ?int rson = 2 * i + 2; ?? ?if (lson < loopSize && b[top] < b[lson]) { ?? ??? ?top = lson; ?? ?} ?? ?if(rson < loopSize&& b[top] < b[rson]) { ?? ??? ?top = rson; ?? ?} ?? ?if (top != i) { ?? ??? ?swap(b[top], b[i]); ?? ??? ?heapify(b, loopSize, top); ?? ?} } void heapSort(int a[], int length) { ?? ?int i; ?? ?for (i = length / 2 - 1; i >= 0; i--) ?? ??? ?heapify(a, length, i); ?? ?for (int i = length - 1; i > 0; i--) { ?? ??? ?swap(a[i], a[0]); ?? ??? ?heapify(a, i, 0); ?? ?} ?? ?for (int j = 0; j < length; j++) { ?? ??? ?cout << a[j] << endl; ?? ?} }
int main() { ?? ?int length = sizeof(A) / sizeof(int); ? ?// sortpaopao(A, length);
//selectionSort(A, length); ?? ?for (int i = 0; i < length; i++) { ?? ??? ?cout << A[i] << endl; ?? ?} ?? ?return 0; }
|